How can I evaluate the result of a logical expression in a string format at runtime in C #?

Say I read this condition from a file:

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

How to check if this condition is true at runtime, provided that "Person" is a class in my code?

+4
source share
3 answers

Although I personally have not done this myself, this may be what you are looking for. This is an expression evaluator that I think you are trying to achieve.

+3
source

It may be redundant to use the Spring Framework for this, but it has a good 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 

The page will open.

+2
source

You can add a link to Microsoft Script Control and start using JavaScript to check your status. 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 re-adding [System.Runtime.InteropServices.ComVisible(true)] you can change the line in AssemblyInfo.cs from [assembly: ComVisible(false)] to [assembly: ComVisible(true)]

+2
source

Source: https://habr.com/ru/post/1380418/


All Articles