Evaluating dynamic string formulas in .NET?
I'm working on a project where I need to evaluate some formulas in VB.NET. I've been using the MS Script Control to evaluate some of the simple logical/mathematical formulas.
However, I'm now faced with dealing with string expressions that set variables in my program to certain values. So, for example, let's s开发者_JAVA百科ay I've got the following:
Dim netPrice As Decimal
Dim expressionFormula As String = "netPrice = 0"
I need to be able to evaluate "expressionFormula" and set the netPrice variable to 0. I've been trying different combinations of the .AddObject method in the MS Script Control, but nothing's worked yet.
I should mention this example is only for illustration purposes, the real scenario involves several DataTable objects from a typed DataSet. In the end, some of the fields in my DataTable may need to be set to specific constant values based on these dynamic expressions.
Thanks for the help!
For this kind of functionality, you will need to write your own parser and evaluator.
Take a look at the Linq Expression
class - it may help.
Alternatively, depending on your approach, you may be able to write and compile dynamic classes using the CSharpCodeProvider
to compile your expressions as C# classes/assemblies.
If you have to handle complex expressions, maybe this library can be helpful : http://flee.codeplex.com/ ?
Dynamic Linq is what you're looking for
精彩评论