Monday, September 23, 2019

c# - Dynamically generated class that implements IEnumerator 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 : IEnumerable
{
public IEnumerator GetEnumerator()
{...}

IEnumerator IEnumerable.GetEnumerator()

{...}

}


This one is output from the Reflector opened my dynamic assembly:



public class SomeClassThatIsIEnumerable : IEnumerable
{
public IEnumerator GetEnumerator()

{
...
}

IEnumerator GetEnumerator()
{
...
}
}



I'm defining my class In such way:



TypeBuilder myType = module.DefineType("myType"...);
myType.AddInterfaceImplementation(typeof(IEnumerable));
myType.AddInterfaceImplementation(typeof(IEnumerable));
myType.AddInterfaceImplementation(typeof(ICollection));
myType.DefineMethodOverride(myDefineGetEnumerator(...),typeof(IEnumerable).GetMethod("GetEnumerator");
myType.DefineMethodOverride(myDefineGetGenericEnumerator(...),typeof(IEnumerable).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?


Answer



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


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...