简体   繁体   English

C#执行变量代码

[英]C# execute variable code

Is it possible to execute code from a string variable, like: 是否可以从字符串变量执行代码,例如:
string mystring = "Console.WriteLine(\\"Hi\\");"; 字符串mystring =“ Console.WriteLine(\\” Hi \\“);”; Is it possible to execute the contents of mystring (printing 'Hi')? 是否可以执行myst​​ring的内容(打印“ 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. 可以使用System.Reflection.Emit或System.CodeDom命名空间,但这并不是一个好主意,因为没有机制可以控制哪些命名空间是允许的。 A user could build a string that would wipe your hard drive. 用户可以构建一个会擦除硬盘驱动器的字符串。

eval()-like functions are huge gaping security holes and should be avoided. 类似eval()的函数是巨大的安全漏洞,应避免使用。 The preferred alternative is a DSL (domain specific language) . 优选的替代方案是DSL(领域专用语言)

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 . 请参阅System.CodeDom命名空间,尤其是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 C#不是动态的或解释性的语言,因此请不要开箱即用

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

How can I evaluate C# code dynamically? 如何动态评估C#代码?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM