[英]Dynamically generated class that implements IEnumerator<T> GetEnumerator() and IEnumerator IEnumerable.GetEnumerator()
I have a problem with Reflection.Emit. 我有一个Reflection.Emit的问题。 I want to have dynamically created class, that has simple implementation of ICollection.
我想拥有动态创建的类,它具有ICollection的简单实现。 All methods I've defined fine, instead of next two: public IEnumerator GetEnumerator() & IEnumerator IEnumerable.GetEnumerator() Next code shows what I want to be in my dynamic class:
我定义的所有方法都很好,而不是下两个:public IEnumerator GetEnumerator()&IEnumerator IEnumerable.GetEnumerator()下一个代码显示了我想要在动态类中的内容:
public class SomeClassThatIsIEnumerable<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator()
{...}
IEnumerator IEnumerable.GetEnumerator()
{...}
}
This one is output from the Reflector opened my dynamic assembly: 这一个是从Reflector输出打开我的动态组件:
public class SomeClassThatIsIEnumerable<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator()
{
...
}
IEnumerator GetEnumerator()
{
...
}
}
I'm defining my class In such way: 我用这样的方式定义我的课程:
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
when I call myType.CreateType TypeLoadException throws with message GetEnumerator method doesn't have implementation. 当我调用myType.CreateType TypeLoadException抛出消息时GetEnumerator方法没有实现。 I'm suggesting on problem with IEnumerable.GetEnumerator method, because I had problems in writing it on C#, not even in IL :).
我建议使用IEnumerable.GetEnumerator方法的问题,因为我在C#上编写它有问题,甚至在IL :)中都没有。 Can anyone help me?
谁能帮我?
It appears you should perhaps be using DefineMethod
rather than DefineMethodOverride
. 您似乎应该使用
DefineMethod
而不是DefineMethodOverride
。 There is an example of emitting an explicit interface implementation on MSDN. 有一个在MSDN 上发出显式接口实现的例子 。 (I have not taken the time to try it however.)
(但我没有花时间尝试它。)
Answer is next define of the method 答案是该方法的下一个定义
MethodBuilder myMethod = myType.DefineMethod("System.Collections.IEnumerable.GetEnumerator",
MethodAttributes.Private | MethodAttributes.HideBySig |
MethodAttributes.NewSlot | MethodAttributes.Virtual |
MethodAttributes.Final);
It was amazing to me that writing an interface name in the name of the method would be to establish a unique relation with the interface 令我惊讶的是,在方法名称中编写接口名称将与接口建立唯一的关系
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.