我对 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 中也没有:)。谁能帮我?