简体   繁体   中英

Parse a Condition written in the String to C# Code and execute the same

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:

  • modify the code you got from the database to be valid JScript (using string methods and probably a lot of Regex)
  • Get an instance of a JScript compiler
  • Compile the code to an assembly
  • Run the assembly with some inputs.

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.

您可以使用EmitCodeDOM生成动态代码,但是最好说一下为什么保存它们,这样可能会有更好的方法来再现它们。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM