我在基于反射的 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 theDynamicMethod
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/