简体   繁体   中英

Execute string as C#

I am checking conditions that could change and so would like to build them in a string and then run that string as C#.

//string conditionToCheck = user.Userdetail.Age > 18
string conditionToCheck = "user." + condition.Table + "." + condition.Column + " " + condition.Operator + " " + condition.Value;
if(conditionToCheck)
{
    ConditionsMet = true;
}

Is there someway to convert conditionToCheck into C# ?


Background

I allow a user to create conditions by selecting a table and it's column and then assign and operator of > < == and a value.

Since a user can select any column of any table in the DB i need the code to check the conditions to handle anything.

Yes, the best solution is probably to use the CodeDOM to dynamically compile C# code. After that you can use reflection to dynamically load and execute your compiled assembly and getting the results from the evaluation. I'm not sure if this is the best or the most elegant solution to your problem however.

You can find an example here

It's not entirely clear to me what you are trying to solve,

but if you are attempting to dynamically convert text to C#

code maybe you should use a T4 solution:

https://msdn.microsoft.com/en-us/library/bb126445.aspx

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