简体   繁体   English

MethodBuilder.CreateDelegate 抛出异常:'派生类必须提供实现。'

[英]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?我想从全局动态方法中获取委托的实例,当我做最后一步时,从 MethodBuilder class 调用 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();
    }

After few minutes, I become understand that the global method is designed for Visual Basic.Net.几分钟后,我明白了全局方法是为 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.但是,您也可以使用 c# 访问它,因此会出现一个问题,即每个方法都必须在 c# 中具有声明类型,因此如果您尝试使用此类功能,您将始终遇到此类异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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