C# 如何使用reflection.emit发出显式接口实现?

C# 如何使用reflection.emit发出显式接口实现?,c#,.net,reflection,reflection.emit,explicit-implementation,C#,.net,Reflection,Reflection.emit,Explicit Implementation,请遵守以下简单的源代码: using System; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; namespace A { public static class Program { private const MethodAttributes ExplicitImplementation = MethodAttributes.Priva

请遵守以下简单的源代码:

using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;

namespace A
{
  public static class Program
  {
    private const MethodAttributes ExplicitImplementation =
      MethodAttributes.Private | MethodAttributes.Virtual | MethodAttributes.Final |
      MethodAttributes.HideBySig | MethodAttributes.NewSlot;
    private const MethodAttributes ImplicitImplementation =
      MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig;

    private static Type EmitMyIntfType(ModuleBuilder moduleBuilder)
    {
      var typeBuilder = moduleBuilder.DefineType("IMyInterface",
        TypeAttributes.NotPublic | TypeAttributes.Interface | TypeAttributes.Abstract);
      typeBuilder.DefineMethod("MyMethod", MethodAttributes.Assembly | MethodAttributes.Abstract |
        MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot,
        typeof(void), new[] { typeof(int) });

      return typeBuilder.CreateType();
    }

    public static void Main()
    {
      var assemblyName = new AssemblyName("DynamicTypesAssembly");
      var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
      var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, assemblyName.Name + ".dll", true);
      var myIntfType = EmitMyIntfType(moduleBuilder);

      var typeBuilder = moduleBuilder.DefineType("MyType",
        TypeAttributes.Public | TypeAttributes.BeforeFieldInit | TypeAttributes.Serializable |
        TypeAttributes.Sealed, typeof(object), new[] { myIntfType });

      //var myMethodImpl = typeBuilder.DefineMethod("IMyInterface.MyMethod", ExplicitImplementation,
      //  null, new[] { typeof(int) });
      var myMethodImpl = typeBuilder.DefineMethod("MyMethod", ImplicitImplementation,
        null, new[] { typeof(int) });
      var ilGenerator = myMethodImpl.GetILGenerator();
      ilGenerator.Emit(OpCodes.Ret);

      var type = typeBuilder.CreateType();
      assemblyBuilder.Save("A.dll");
    }
  }
}
下面是通过使用Reflector反编译A.dll程序集获得的等效C#代码:

internal interface IMyInterface
{
    void MyMethod(int);
}
[Serializable]
public sealed class MyType : IMyInterface
{
    public override void MyMethod(int)
    {
    }
}
现在,如果我希望
MyType
类型显式实现
IMyInterface
接口,该怎么办? 因此,我采取以下措施:

//var myMethodImpl = typeBuilder.DefineMethod("IMyInterface.MyMethod", ExplicitImplementation,
//  null, new[] { typeof(int) });
var myMethodImpl = typeBuilder.DefineMethod("MyMethod", ImplicitImplementation,
  null, new[] { typeof(int) });
并切换注释以生成此代码:

var myMethodImpl = typeBuilder.DefineMethod("IMyInterface.MyMethod", ExplicitImplementation,
  null, new[] { typeof(int) });
// var myMethodImpl = typeBuilder.DefineMethod("MyMethod", ImplicitImplementation,
//  null, new[] { typeof(int) });
但是现在,应用程序无法创建动态类型。这一行:

var type = typeBuilder.CreateType();
引发以下异常:

System.TypeLoadException was unhandled
  Message="Method 'MyMethod' in type 'MyType' from assembly 'DynamicTypesAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation."
  Source="mscorlib"
  TypeName="MyType"
  StackTrace:
       at System.Reflection.Emit.TypeBuilder._TermCreateClass(Int32 handle, Module module)
       at System.Reflection.Emit.TypeBuilder.TermCreateClass(Int32 handle, Module module)
       at System.Reflection.Emit.TypeBuilder.CreateTypeNoLock()
       at System.Reflection.Emit.TypeBuilder.CreateType()
       at A.Program.Main() in C:\Home\work\A\Program.cs:line 45
  InnerException: 
有人能告诉我我的代码有什么问题吗

谢谢。

这似乎与

其中:

但是,要提供一个单独的 I.M()的实现,您必须 定义一个方法体,然后使用
definemethodverride
方法 将该方法体与
MethodInfo
表示I.M()。这个 方法体的名称不正确 重要


的确是这样,虽然我确实注意到了这个问题,甚至浏览了MSDN的文章,但在阅读了备注部分的第一段之后就放弃了它。只是不认为显式接口实现为接口方法提供了另一个名称。现在我明白我的错误了。谢谢
        // Build the method body for the explicit interface 
        // implementation. The name used for the method body 
        // can be anything. Here, it is the name of the method,
        // qualified by the interface name.
        //
        MethodBuilder mbIM = tb.DefineMethod("I.M", 
            MethodAttributes.Private | MethodAttributes.HideBySig |
                MethodAttributes.NewSlot | MethodAttributes.Virtual | 
                MethodAttributes.Final,
            null,
            Type.EmptyTypes);
        ILGenerator il = mbIM.GetILGenerator();
        il.Emit(OpCodes.Ldstr, "The I.M implementation of C");
        il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", 
            new Type[] { typeof(string) }));
        il.Emit(OpCodes.Ret);

        // DefineMethodOverride is used to associate the method 
        // body with the interface method that is being implemented.
        //
        tb.DefineMethodOverride(mbIM, typeof(I).GetMethod("M"));