How can I evaluate C# code dynamically?

后端 未结 16 2130
[愿得一人]
[愿得一人] 2020-11-22 03:37

I can do an eval(\"something()\"); to execute the code dynamically in JavaScript. Is there a way for me to do the same thing in C#?

An example of what I

16条回答
  •  离开以前
    2020-11-22 04:08

    I have written an open source project, Dynamic Expresso, that can convert text expression written using a C# syntax into delegates (or expression tree). 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.SomeMethod() : 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 .

提交回复
热议问题