Dynamically generated class that implements IEnumerator<T> GetEnumerator() and IEnumerator IEnumerable.GetEnumerator()
I have a problem with Reflection.Emit. I want to have dynamically created class, that has simple implementation of 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 class SomeClassThatIsIEnumerable<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator()
{...}
IEnumerator IEnumerable.GetEnumerator()
{...}
}
This one is output from the Reflector opened my dynamic assembly:
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&l开发者_JS百科t;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. I'm suggesting on problem with IEnumerable.GetEnumerator method, because I had problems in writing it on C#, not even in IL :). Can anyone help me?
It appears you should perhaps be using DefineMethod
rather than DefineMethodOverride
. There is an example of emitting an explicit interface implementation on 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
精彩评论