如何在C#中的运行时以字符串格式计算布尔表达式的结果?

让我们说我从文件中读取了这个条件:

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

如果“Person”是我的代码中的类,如何在运行时检查此条件是否为真?

虽然我自己没有亲自完成这项工作, 但这可能正是您所寻求的。 这是一个表达式评估器,这是我认为你想要实现的。

为此使用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 

检查文档页面 。

您可以添加对Microsoft Script Control的引用,并开始使用JavaScript来检查您的状况。 这是一个简单的例子

 [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"); } } 

要避免重复添加[System.Runtime.InteropServices.ComVisible(true)]您可以将AssemblyInfo.cs中的行从[assembly: ComVisible(false)]更改为[assembly: ComVisible(true)]