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
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.