有没有简单的方法可以在 C# 中创建方法并动态设置其主体?
我将方法的主体存储为字符串,并且我希望动态创建此方法。但是,我不确定如何分配它的主体。我遇到过一种使用 CodeDom 的相当复杂的方法,以及另一种使用 Emit 和 OpCodes 的方法。是否有更简单的方法来利用字符串变量中的现有代码?
string method_body = "return \"Hello, world!\";"; // there is a method body
DynamicMethod dm = new System.Reflection.Emit.DynamicMethod("My_method",
typeof(string), new Type[] { }); // some way to create method dynamically
// any way to set body?
string result = (string)dm.Invoke(...); // I need to write result in a variable
I have the body of a method stored as a string and I'm looking to create this method dynamically. However, I'm unsure how to assign its body. I've come across a rather complex method using CodeDom, and another using Emit with OpCodes. Is there a simpler way to utilize the existing code from a string variable?
string method_body = "return \"Hello, world!\";"; // there is a method body
DynamicMethod dm = new System.Reflection.Emit.DynamicMethod("My_method",
typeof(string), new Type[] { }); // some way to create method dynamically
// any way to set body?
string result = (string)dm.Invoke(...); // I need to write result in a variable
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
听起来你想要的是“编译器即服务”。这不在 MS .NET 4.0 中,但可能在更高版本中。不过它已经在 Mono 中了。在此之前,可用的选项有:
CSharpCodeProvider
,但您必须通过反射将其作为方法加载(并为其创建委托)CodeDom
Reflection.Emit
Expression
在 4.0 中,
Expression
API 比 3.5 中丰富得多,允许大多数常见的构造,而无需Expression
的痛苦。代码>CodeDom。但不要低估Reflection.Emit
- 需要一些时间来了解ILGenerator
并使用堆栈,但它并不像人们想象的那么糟糕思考。附带说明一下,除非您只想执行一次,否则不要使用
DynamicMethod
中的Invoke
。更好的方法是使用CreateDelegate
,然后存储(并重新使用)该委托:或者使用
Expression
API:It sounds like what you want is the "compiler as a service". That is not in MS .NET 4.0, but may be in a later release. It is already in Mono, though. Until then, the options available are:
CSharpCodeProvider
, but you'll have to load it in as a method (and create a delegate to it) via reflectionCodeDom
Reflection.Emit
Expression
In 4.0, the
Expression
API is far richer than it was in 3.5, allowing most common constructs without the pain ofCodeDom
. But don't discountReflection.Emit
- it takes a little while to get your head aroundILGenerator
and using the stack, but it isn't as bad as people tend to think.As a side-note, don't use
Invoke
fromDynamicMethod
unless you only want to execute it once. The better approach is to useCreateDelegate
, then store (and re-use) that delegate:Or with the
Expression
API:您需要查看这些命名空间:
这可能会帮助您入门:http: //www.west-wind.com/presentations/dynamicCode/DynamicCode.htm
You need to take a look at these namespaces:
This may get you started: http://www.west-wind.com/presentations/dynamicCode/DynamicCode.htm
将其保存到 .CS 文件并即时编译和执行。
Save this to a .CS file and compile and execute it on the fly.