在运行时在C#字符串转换为可执行的代码? [英] Convert string to executable code at run time in c#?

查看:904
本文介绍了在运行时在C#字符串转换为可执行的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法,我可以在C#在运行时的代码字符串转换成可执行代码?



所以,如果我有谓词的文件

 这是一个txt文件
U普通文本=> u.Contains(机器人)及和放大器; u.Contains(WebKit的)
U => u.Contains(简称iPhone)及和放大器; u.Contains(WebKit的)



我希望通过我的程序读取它,然后捕获每个谓词作为一个字符串,然后将其转换为动态代码。是这样的:

 的String [] =谓词///获取文件contentsa 

的foreach(VAR谓语谓词)
{
如果(userAgent.ConformsTo(EVAL(谓语)))返回true;
}


解决方案

您可以使用的 CSharpCodeProvider 一流的,但你需要建立相当多的额外代码周围的片断,因为你必须提供一个完整的类。我这样做是为C#中的深度我的Snippy工具,可以下载源得到一个它是如何做到简单的例子。



然而,生活正在成为在这个领域与的罗斯林 - 你可能希望得到的 CTP 和探索。


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.

这篇关于在运行时在C#字符串转换为可执行的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆