这听起来很明显,但我遇到了很多困难。基本上,我正在做的是使用 Reflection.Emit 生成一个方法,然后我想调用它。到目前为止,我有方法构建等,但是在构建方法之后我无法获得对该方法的引用,因为“在创建类型之前不支持调用的成员。”
这是我基本上做的事情:
AssemblyBuilder assembly;
ModuleBuilder module;
TypeBuilder containerTypeBuilder;
Type containerType;
var name = new AssemblyName();
name.Name = "DynamicWrapper";
var domain = Thread.GetDomain();
assembly = domain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave);
module = assembly.DefineDynamicModule(assembly.GetName().Name, false);
containerTypeBuilder = module.DefineType("__DynamicWrapperType",
TypeAttributes.Public | TypeAttributes.Class |
TypeAttributes.AutoClass |
TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit |
TypeAttributes.AutoLayout, typeof(object));
//build method
var mb = containerTypeBuilder.DefineMethod("generatedmethod" + (unique++),
MethodAttributes.Public | MethodAttributes.Static, typeof (int),
new Type[] {});
//build method body and all that
.....
var type=module.GetType("__DynamicWrapperType");
var info=type.GetMethod(mb.Name, BindingFlags.Static | BindingFlags.Public); //error here
如何获取新构建的方法并加载它以便我可以调用它?
另外,我试过mb.Invoke
了,但这会产生“动态模块不支持调用的成员”。