Convert string to executable code at run time in c#?

ぃ、小莉子 提交于 2019-11-29 23:33:12

问题


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;
}

回答1:


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.




回答2:


Have a look at the Roslyn ScriptEngine.



来源:https://stackoverflow.com/questions/8321734/convert-string-to-executable-code-at-run-time-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!