I want to get an instance of delegate from a global dynamic method, when I do the final step, invoke the method of CreateDelegate from MethodBuilder class, It throws such exception, I tried to locate the code source of .net framework to find why, but failed, will any one could help me to resolve this problem?
[TestMethod]
public void Test()
{
//THESE CODE COPIES FROM MSDN
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("TempAssembly"), AssemblyBuilderAccess.RunAndCollect);
ModuleBuilder module = assembly.DefineDynamicModule("TempModule");
MethodBuilder method = module.DefineGlobalMethod
("MyMethod1", MethodAttributes.Static | MethodAttributes.Public,
null, null);
ILGenerator generator = method.GetILGenerator();
generator.EmitWriteLine("Hello World from global method.");
generator.Emit(OpCodes.Ret);
// Fix up the 'TempModule' module .
module.CreateGlobalFunctions();
//ERROR:
Action action = method.CreateDelegate(typeof(Action), null) as Action;
action();
}
After few minutes, I become understand that the global method is designed for Visual Basic.Net. However, you can access it with c# also, so this get a problem that each method must have a declaring type in c#, so if you try to use such functions, you will always get such exception.