-->

How can I evaluate the result of a boolean express

2020-07-18 04:56发布

问题:

Lets say I read this condition from a file:

Condition = "Person.Value.Status == 9"

How can I check if this condition is true in runtime providing that "Person" is a class in my code?

回答1:

While I haven't personally done this myself, this might be what you're looking for. It's an expression evaluater which is what I think you are trying to achieve.



回答2:

It may be an overkill to use Spring Framework for this, but it does have nice expression evaluator.

ExpressionEvaluator.GetValue(null, "2 == 2")  // true

ExpressionEvaluator.GetValue(null, "date('1974-08-24') != DateTime.Today")  // true

ExpressionEvaluator.GetValue(null, "2 < -5.0") // false

ExpressionEvaluator.GetValue(null, "DateTime.Today <= date('1974-08-24')") // false

ExpressionEvaluator.GetValue(null, "'Test' >= 'test'") // true

Check documentation page.



回答3:

You can add a reference to Microsoft Script Control and start to use JavaScript to check your condition. Here is a simple example

[System.Runtime.InteropServices.ComVisible(true)]
public partial class Form1 : Form
{
    [System.Runtime.InteropServices.ComVisible(true)]    
    public class Person
    {
        public int Status = 9;
    }

    public Person person = new Person();

    private void Form1_Load(object sender, EventArgs e)
    {
        MSScriptControl.ScriptControlClass script = new MSScriptControl.ScriptControlClass();
        script.Language = "JavaScript";

        script.AddObject("myform", this,true); 

        var b =  script.Eval("myform.person.Status==9");
    }
}

To avoid to repeatedly add [System.Runtime.InteropServices.ComVisible(true)] You can change the line in AssemblyInfo.cs from [assembly: ComVisible(false)] to [assembly: ComVisible(true)]