简体   繁体   中英

Evaluate expression as string, return object?

Basically I have some code where when it happens, I need to set some object equal to some expression. All of this "what to do" jazz is stored as a string. So I parse it, and use reflection to find the object I am doing it to. Now I need to find out how to store the value to this object. The problem is the value could be "1", "1*(5/2)", or "some string value". It would be really cool if I could have expressions like "this.SomeProperty" or "(x > 3 ? 4 : 5)".

Also, the object it is storing to, could be a string, int, double, or float at the minimum.

The VS2008 samples included a nifty ExpressionParser which could be used as a generic expression parser ( VS2008 Samples ). With a few small updates, and a custom factory class, we can turn it into something a bit more expressive:

string expression = "(1 + 2)";
var func = FunctionFactory.Create<int>(expression);

Or:

expression = "(a * b)";
var func2 = FunctionFactory.Create<int, int, int>(expression, new[] { "a", "b" });

The return types of these Create methods are Func<> instances, which means we get nice strongly type delegates:

int result = func2(45, 100); // result = 450;

I've push the code to a gist

Update : I've recently blogged about this too.

Update 2 , another example:

var person = new Person { Age = 5 };
string expression = "(Age == 5)";
var func3 = FunctionFactory.Create<Person, bool>(expression);

bool isFive = func3(person); // Should be true.

Have you seen http://ncalc.codeplex.com ?

It's extensible, fast (eg has its own cache) enables you to provide custom functions and varaibles at run time by handling EvaluateFunction/EvaluateParameter events. Example expressions it can parse:

Expression e = new Expression("Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)"); 

  e.Parameters["Pi2"] = new Expression("Pi * Pi"); 
  e.Parameters["X"] = 10; 

  e.EvaluateParameter += delegate(string name, ParameterArgs args) 
    { 
      if (name == "Pi") 
      args.Result = 3.14; 
    }; 

  Debug.Assert(117.07 == e.Evaluate()); 

It also handles unicode & many data type natively. It comes with an antler file if you want to change the grammer. There is also a fork which supports MEF to load new functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM