Example:
Condition:
IF A > B THEN
PRINT B
ELSE
PRINT A
This condition is written as a string in coloumn of the table in SQL.
I want to fetch this condition from the table and convert this condition to the C# Code as
If(A > B )
{
print B...........
}
else
{
print A...........
}
Where A and B are the Dynamic values passed from the solution Suppose A=10 and B=20 then
execute the code which will return 10 or 20 base on the condition.
It depends a bit on what you want to do with this, but one possible way to solve this is to use the Microsoft.JScript assembly. Although JScript is a tad different from c#, much of the syntax is the same or similar. What's more, JScript is based on a global scope, so no need to wrap the code you generated in a method either.
In steps you would do the following:
But since this is rather heavy on the creation of types/assemblies (that might not be unloadable), I would recommend (using the above method) compiling a simple wrapper for the jscript eval() function, and simply providing your jscript to that code. Then you won't have to worry about compilation etc.
Be carefull when creating dynamic code though. The whole of the .Net framework would be avaliable for use, so unless you absolutely trust the source of the conditions, or restricted the compiled assembly, nasty stuff™ could happen.
There is an answer here on SO that explain how to reuse the Javascript engine DLL that's shipped with every Windows installation: parse and execute JS by C# .
It has a sample with a function that you could adapt to your need.
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.