开发者

Program code as a string

This is not really for practical use, but is there any way to execute a string as a program code in C#?

For example :

instead of writing

Console.WriteLine("blah blah blah");

I wo开发者_StackOverflowuld like to write something like

string s = "Console.WriteLine(\"blah blah blah\")"
execute(s);


The only way I can think of doing this is by compiling your code at runtime. Here is an article that explains how to do this http://simeonpilgrim.com/blog/2007/12/04/compiling-and-running-code-at-runtime/


I know it's not exactly what you asked for (although you didn't mention a the language of the program in the string), but IronPython is very cool: http://secretgeek.net/host_ironpython.asp, http://blogs.msdn.com/b/abhinaba/archive/2006/02/09/528416.aspx.

Also (as boca already mentioned) runtime compilation worked well, too: Is it possible to dynamically compile and execute C# code fragments?


It is possible in C#, but it is intentionally difficult. There's no simple "exec()" function you can use out of the box.

AFAIK this is by design. Exec functions are big gaping security holes, because they expose the full power of the language to users who often should not have that power. As the programmer, you often intend to use an exec() function to allow a user to enter simple math or string expressions, and suddenly you have a hacker come along and instantiate a System.Net.WebClient and use it to download and execute something much more malicious. There is no way to limit which assemblies are allowed.

The preferred alternative in .Net languages is something called a Domain Specific Language (DSL). A DSL is a (relatively) easy way to define your own grammar (and the meaning behind it) for what kinds of things you want to allow the user to do, without the security implications of giving them access to the whole base class library. It also has the advantage of allowing you to provide specialized operations at a higher level than they might otherwise be available.


This can be done using Microsoft.CSharp.CSharpCodeProvider.

Check this.


You can do this using CodeDOM. See Using the CodeDOM at MSDN.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜