A dynamically generated class that implements IEnumerator <T> GetEnumerator () and IEnumerator IEnumerable.GetEnumerator ()

I have a problem with Reflection.Emit. I want to have a dynamically created class that has a simple implementation of ICollection. All the methods that I defined perfectly, instead of the following two: public IEnumerator GetEnumerator () and IEnumerator IEnumerable.GetEnumerator () The following code shows that I want to be in my dynamic class:

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

    IEnumerator IEnumerable.GetEnumerator()
    {...}

}

This output is derived from the reflector that opened my dynamic assembly:

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

        IEnumerator GetEnumerator()
        {
           ...
        }
    }

I define my class this 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

myType.CreateType TypeLoadException GetEnumerator . IEnumerable.GetEnumerator, #, IL:). - ?

+3
2

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

,

+1

, DefineMethod, DefineMethodOverride. MSDN. ( , , .)

+2

Source: https://habr.com/ru/post/1774470/


All Articles