简体   繁体   中英

C# execute variable code

Is it possible to execute code from a string variable, like:
string mystring = "Console.WriteLine(\\"Hi\\");"; Is it possible to execute the contents of mystring (printing 'Hi')?

It's possible using the System.Reflection.Emit or System.CodeDom namespaces, but it's not exactly a good idea as there's no mechanism to control what namespaces are and are not allowed. A user could build a string that would wipe your hard drive.

eval()-like functions are huge gaping security holes and should be avoided. The preferred alternative is a DSL (domain specific language) .

Yes. Fire up the compiler at runtime and pass in your code. It will spit out executable code. See the System.CodeDom namespace, especially, System.CodeDom.Compiler .

使用代码DOM

Need to use reflection to get something like that. C# is not dynamic or interpreted language, so you dont get it out of the box

http://www.codeproject.com/KB/dotnet/Expr.aspx

How can I evaluate C# code dynamically?

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