eval(string) to C# code

后端 未结 8 1951
傲寒
傲寒 2021-01-19 04:23

Is it possible to evaluate the following in C# at runtime

I have a class that contains 3 properties (Field,Operator,Value)

8条回答
  •  不知归路
    2021-01-19 05:07

    Disclaimer: I'm the owner of the project Eval Expression.NET

    This library is close to being the JS Eval equivalent. You can almost evaluate and compile all the C# language.

    Here is a simple example using your question, but the library goes way beyond this simple scenario.

    int field = 2;
    int value = 1;
    string binaryOperator = ">";
    
    string formula = "x " + binaryOperator + " y";
    
    // For single evaluation
    var value1 = Eval.Execute(formula, new { x = field, y = value });
    
    // For many evaluation
    var compiled = Eval.Compile>(formula, "x", "y");
    var value2 = compiled(field, value);
    

提交回复
热议问题