eval(string) to C# code

后端 未结 8 1945
傲寒
傲寒 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<bool>(formula, new { x = field, y = value });
    
    // For many evaluation
    var compiled = Eval.Compile<Func<int, int, bool>>(formula, "x", "y");
    var value2 = compiled(field, value);
    
    0 讨论(0)
  • 2021-01-19 05:07

    CSharpCodeProvider; switch statements that pick the proper different "operators"; the DLR... they are all ways you could do this; but they seem weird solutions to me.

    How about just using delegates?

    Assuming your Field and Value are numbers, declare something like this:

    delegate bool MyOperationDelegate(decimal left, decimal right);
    ...
    class Rule {
        decimal Field;
        decimal Value;
        MyOperationDelegate Operator;
    }
    

    Now you can define your 'rule' as, for example, a bunch of lambdas:

    Rule rule1 = new Rule;
    rule1.Operation = (decimal l, decimal r) => { return l > r; };
    rule1.Field = ... 
    

    You can make arrays of rules and apply them whichever way you wish.

    IEnumerable<Rule> items = ...;
    
    foreach(item in items)
    {
        if (item.Operator(item.Field, item.Value))
        { /* do work */ }
    }
    

    If Field and Values are not numbers, or the type depends on the specific rule, you can use object instead of decimal, and with a little bit of casting you can make it all work.

    That's not a final design; it's just to give you some ideas (for example, you would likely have the class evaluate the delegate on its own via a Check() method or something).

    0 讨论(0)
提交回复
热议问题