Given a dynamic if statement in a String is there a method in .net to evaluate and return the correct result.
IE
static void Main(string[] args)
{
String a = "if(\"Alex\" == \"Alex\"){return 1;}else{return 0;}";
passThroughTest.Program.evalStatement(a);
}
public static void evalStatement(String statement)
{
//Evaluation of Statement
}
This isn't perfect but in this case the end result would be a 1. This seems 'stupid' from this point of view, but its for a more complex engine which needs to draw on similar syntax to evaluate.
Am I at a point where I need to write a parser of some sort and evaluate the statements...?
Thanks for your help!
What I think you are looking for is the CSharpCodeProvider : http://msdn.microsoft.com/en-us/library/microsoft.csharp.csharpcodeprovider.aspx
This allows you to compile or evaluate C# code from a source and run it. It might not be as easy as evaluating a single "if" case, as when you compile C#, you are expected to have the whole syntax coming with it.
You can use javascript.net
Sample code from their website:
// Initialize a context using (JavascriptContext context = new JavascriptContext()) { // Setting external parameters for the context context.SetParameter("console", new SystemConsole()); context.SetParameter("message", "Hello World !"); context.SetParameter("number", 1); // Script string script = @" var i; for (i = 0; i < 5; i++) console.Print(message + ' (' + i + ')'); number += i; "; // Running the script context.Run(script); // Getting a parameter Console.WriteLine("number: " + context.GetParameter("number")); }
Or use C# expression tree, see Building Expression Evaluator with Expression Trees
You can also do something like this:
var expression="(\"Alex\" == \"Alex\") ? 1:0";
var res = FlexRule.DynamicEvaluation.ExpressionEval.Default.Compute(null, expression);
For more details information of expression please have a look at http://wiki.flexrule.com/index.php?title=Expression
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.