Evaluating Expression at Runtime

2019-04-10 09:12发布

I have a C# Console Application project.

I have a logical expression that is stored in database as nvarchar.

For example, the stored expression is: ((34 > 0) || (US == ES)) && (4312 = 5691)

While my application running, I want to retrieve the expression and evaluate it so that the result will be true or false.

How can I do it at runtime?

2条回答
男人必须洒脱
2楼-- · 2019-04-10 10:04

You can parse the expression into the .NET Expression class and compile and run it in order to get the result.

The class already supports all the logical operations you have in your example, though it appears to be ambiguous (you are using both == and = in a very similar manner).

You will have to write your own parser/converter though.

查看更多
淡お忘
3楼-- · 2019-04-10 10:09

Here's a rather unusual solution, involving JScript:

  • Create a JScript class with the following code:

    public class JsMath {
        public static function Eval(expression:String) : Object {
            return eval(expression);
        }
    }
    
  • Compile it into a DLL:

    jsc /target:library /out:JsMath.dll JsMath.js
    
  • In your C# project, reference JsMath.dll and Microsoft.JScript.dll

  • Now you can use the Eval method as follows:

    string expression = "((34 > 0) || ('US' == 'ES')) && (4312 == 5691)";
    bool result = (bool)JsMath.Eval(expression);
    

Benefits:

  • no work required to parse the expression, the JScript engine does it for you
  • no need to compile arbitrary code (which can be a big security hole if the code is entered by the user)
  • should work with any simple mathematical or logical expression, as long as it follows the JScript syntax

Drawbacks:

  • no way to pass variables (as far as I know)
  • requires a reference to the JScript assembly (not a big issue in most cases, but I'm not sure this assembly is available in the Client Profile or in Silverlight)
查看更多
登录 后发表回答