[英]How can I evaluate the result of a boolean expression in string format on runtime in C#?
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? 如果“Person”是我的代码中的类,如何在运行时检查此条件是否为真?
It may be an overkill to use Spring Framework for this, but it does have nice expression evaluator. 为此使用Spring Framework可能有点过分,但它确实有很好的表达式求值器。
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 . 检查文档页面 。
You can add a reference to Microsoft Script Control
and start to use JavaScript to check your condition. 您可以添加对
Microsoft Script Control
的引用,并开始使用JavaScript来检查您的状况。 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)]
要避免重复添加
[System.Runtime.InteropServices.ComVisible(true)]
您可以将AssemblyInfo.cs中的行从[assembly: ComVisible(false)]
更改为[assembly: ComVisible(true)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.