[英]How can I evaluate the result of a boolean expression in string format on runtime in 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)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.