MethodBuilder.CreateDelegate引发异常:“派生类必须提供实现。”

时间:2019-09-27 05:29:12

标签: c# typebuilder

我想从全局动态方法中获取委托的实例,当我执行最后一步时,从MethodBuilder类调用CreateDelegate的方法,它抛出此类异常,我尝试将.net框架的代码源定位到找出原因,但失败了,有谁能帮助我解决这个问题?

    [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();
    }

1 个答案:

答案 0 :(得分:0)

几分钟后,我了解到全局方法是为Visual Basic.Net设计的。 但是,您也可以使用c#来访问它,因此会出现一个问题,即每个方法在c#中都必须具有声明类型,因此,如果尝试使用此类函数,则始终会得到此类异常。