5

我对 Reflection.Emit 有疑问。我想要动态创建的类,它具有 ICollection 的简单实现。我定义的所有方法都很好,而不是接下来的两个: public IEnumerator GetEnumerator() & IEnumerator IEnumerable.GetEnumerator() 下一个代码显示了我想要在我的动态类中的内容:

public class SomeClassThatIsIEnumerable<T> : IEnumerable<T>
{
    public IEnumerator<T> GetEnumerator()
    {...}

    IEnumerator IEnumerable.GetEnumerator()
    {...}

}

这是反射器的输出,打开了我的动态程序集:

public class SomeClassThatIsIEnumerable<T> : IEnumerable<T>
    {
        public IEnumerator<T> GetEnumerator()
        {
           ...
        }

        IEnumerator GetEnumerator()
        {
           ...
        }
    }

我正在以这种方式定义我的班级:

TypeBuilder myType = module.DefineType("myType"...);
myType.AddInterfaceImplementation(typeof(IEnumerable));
myType.AddInterfaceImplementation(typeof(IEnumerable<T>));
myType.AddInterfaceImplementation(typeof(ICollection<T>));
myType.DefineMethodOverride(myDefineGetEnumerator(...),typeof(IEnumerable).GetMethod("GetEnumerator");
myType.DefineMethodOverride(myDefineGetGenericEnumerator(...),typeof(IEnumerable<T>).GetMethod("GetEnumerator);
//Definitions of other ICollection methods
//Define GetEnumerator is looks like this:
MethodBuilder method = myType.DefineMethod("GetEnumerator", MethodAttributes.Final | MethodAttributes.Virtual...)
ILGenerator il = method.GetILGenerator();
// adding opcodes

当我调用 myType.CreateType TypeLoadException 时抛出消息 GetEnumerator 方法没有实现。我建议使用 IEnumerable.GetEnumerator 方法的问题,因为我在 C# 上编写它时遇到了问题,甚至在 IL 中也没有:)。谁能帮我?

4

2 回答 2

2

看来您可能应该使用DefineMethod而不是DefineMethodOverride. 在 MSDN 上有一个发出显式接口实现的示例。(不过我还没有花时间去尝试。)

于 2010-11-12T10:27:00.643 回答
1

答案是方法的下一个定义

 MethodBuilder myMethod = myType.DefineMethod("System.Collections.IEnumerable.GetEnumerator",
                   MethodAttributes.Private | MethodAttributes.HideBySig |
                MethodAttributes.NewSlot | MethodAttributes.Virtual | 
                MethodAttributes.Final);

让我惊讶的是,在方法名称中写一个接口名称会与接口建立唯一的关系

于 2010-11-13T15:31:52.497 回答