How can I evaluate the result of a boolean express

2020-07-18 05:04发布

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?

3条回答
甜甜的少女心
2楼-- · 2020-07-18 05:17

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.

查看更多
▲ chillily
3楼-- · 2020-07-18 05:28

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.

查看更多
Juvenile、少年°
4楼-- · 2020-07-18 05:35

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

查看更多
登录 后发表回答