简体   繁体   中英

MethodBuilder.CreateDelegate throws exception:'Derived classes must provide an implementation.'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM