How can I evaluate a C# expression dynamically?

后端 未结 7 1330
情话喂你
情话喂你 2020-11-22 07:22

I would like to do the equivalent of:

object result = Eval(\"1 + 3\");
string now    = Eval(\"System.DateTime.Now().ToString()\") as string

7条回答
  •  温柔的废话
    2020-11-22 08:03

    I have written an open source project, Dynamic Expresso, that can convert text expression written using a C# syntax into delegates (or expression tree). Text expressions are parsed and transformed into Expression Trees without using compilation or reflection.

    You can write something like:

    var interpreter = new Interpreter();
    var result = interpreter.Eval("8 / 2 + 2");
    

    or

    var interpreter = new Interpreter()
                    .SetVariable("service", new ServiceExample());
    
    string expression = "x > 4 ? service.aMethod() : service.AnotherMethod()";
    
    Lambda parsedExpression = interpreter.Parse(expression, 
                            new Parameter("x", typeof(int)));
    
    parsedExpression.Invoke(5);
    

    My work is based on Scott Gu article http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx .

提交回复
热议问题