Is there any way I can convert a string of code into executable code at runtime in c#?
So if I have a file of predicates
This is normal text in a txt file
u => u.Contains("android") && u.Contains("webkit")
u => u.Contains("iphone") && u.Contains("webkit")
I would want to read it in via my program and then capture each predicate as a string and then convert it to code on the fly. Something like:
string[] predicates = ///get file contentsa
foreach(var predicate in predicates)
{
if(userAgent.ConformsTo(eval(predicate))) return true;
}
You can use CSharpCodeProvider
class, but you'll need to build quite a bit of extra code around the snippet, as you have to provide a full class. I did this for my "Snippy" tool for C# in Depth, and you can download the source to get one simple example of how it can be done.
However, life is becoming much simpler in this area with Roslyn - you may want to get hold of the CTP and explore that.
Have a look at the Roslyn ScriptEngine.
来源:https://stackoverflow.com/questions/8321734/convert-string-to-executable-code-at-run-time-in-c