.net - 什么是动态方法,DynamicMethod 与 MethodBuilder 有何不同?

标签 .net reflection clr reflection.emit dynamic-method

我在基于反射的 C# 代码中遇到过一些动态方法,但我还没有弄清楚它们到底是什么。似乎有一个 DynamicMethod允许在运行时生成和规范 CLR 方法的类。但是还有 MethodBuilder类(class)。他们似乎都在做非常相似的事情。显然“动态程序集”是 AssemblyBuilder类和“动态类型”是 TypeBuilder类。他们都住在System.Reflection.Emit无论如何命名空间。

MSDN 似乎有关于这个主题的宝贵的少量高级信息。因此,如果有人可以解释什么是动态方法,那么 XYZBuilder 到底在哪里?类在这里发挥作用,它们各自的用途,那就太好了。我应该知道的任何其他 Reflection.Emit 类型和功能也将不胜感激。

最佳答案

我认为 the documentation for DynamicMethod 很好地解释了这一点:

You can use the DynamicMethod class to generate and execute a method at run time, without having to generate a dynamic assembly and a dynamic type to contain the method. The executable code created by the just-in-time (JIT) compiler is reclaimed when the DynamicMethod object is reclaimed. Dynamic methods are the most efficient way to generate and execute small amounts of code.



如果需要动态创建一个或多个方法,请使用 DynamicMethod .如果要创建整个类型,则意味着您需要创建一个动态程序集( AssemblyBuilder ),然后在其中创建一个模块( ModuleBuilder ),然后创建一个或多个类型( TypeBuilder )。要在这些类型中创建方法,您可以使用 MethodBuilder .

另一个区别是 GC:DynamicMethod s 总是可以被垃圾回收,它们被一一回收。也就是说,任何方法只要你停止使用它就可以被收集。另一方面,动态程序集只有在您指定它时才能收集(通过使用 AssemblyBuilderAccess.RunAndCollect ),并且它们总是逐个程序集地收集。例如,如果您在一个程序集中有两种类型,而您只使用其中一种,则无法收集另一种。

关于.net - 什么是动态方法,DynamicMethod 与 MethodBuilder 有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9755991/

相关文章:

.net - 通过 WCF 发送 XML 是否存在问题?

java - 如何从动态代理中解包原始对象

c# - 强制转换与在 CLR 中使用 'as' 关键字

c# - 静态通用类作为字典

c# - .xps 文件的正确内容类型是什么

.net - Linq2Sql 与存储过程

java - 如何知道方法是否使用反射将数组作为参数

.net - 编写使用 .NET 的语言的优点、缺点和困难

c# - 事件查看器,如何以编程方式向其添加 “task”

Java - 获取接口(interface)中方法的签名,其代理实现也是如此