简体   繁体   English

将表达式计算为字符串,返回对象?

[英]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". 问题是值可能是“1”,“1 *(5/2)”或“某个字符串值”。 It would be really cool if I could have expressions like "this.SomeProperty" or "(x > 3 ? 4 : 5)". 如果我能有像“this.SomeProperty”或“(x> 3?4:5)”这样的表达式,那真的很酷。

Also, the object it is storing to, could be a string, int, double, or float at the minimum. 此外,它存储的对象可以是字符串,int,double或float。

The VS2008 samples included a nifty ExpressionParser which could be used as a generic expression parser ( VS2008 Samples ). VS2008样本包括一个漂亮的ExpressionParser ,它可以用作通用表达式解析器( VS2008样本 )。 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: 这些Create方法的返回类型是Func<>实例,这意味着我们得到了很好的强类型委托:

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: 更新2 ,另一个例子:

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 ? 你见过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. 它的可扩展性,快速性(例如,具有自己的缓存)使您能够通过处理EvaluateFunction / EvaluateParameter事件在运行时提供自定义函数和变量。 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. 它还可以本地处理unicode和许多数据类型。 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. 还有一个支持MEF加载新功能的fork。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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