eval(string) to C# code

后端 未结 8 1948
傲寒
傲寒 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

    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 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).

提交回复
热议问题