I am having a problem calling a delegate whose type is not completed at the time of emitting. I will clarify: I declared the following delegate type:
// Delegate type. The 'firstArgument' will be 'this', i.e., this is an open
// instance method: the implicit argument is here given explicitly, in
// 'firstArgument'. (See link below for explanation on open instance delegates).
public delegate Object DirectReadAccessor<T>(T firstArgument);
And now I'm trying to dynamically (i.e. using TypeBuilder) create the following class:
public MyClass {
private static DirectReadAccessor<MyClass>[] directReadAccessors;
public Object DirectRead(int i) {
directReadAccessors[i](this);
}
public static void InitializeClass(MethodInfo[] directReadAccessorsMInfo) {
int length = directReadAccessorsMInfo.Length;
Type[] typeArguments = new Type[] { typeof(MyClass) };
directReadAccessors = new DirectReadAccessor<MyClass>[length];
for (int i = 0; i < length; i++) {
directReadAccessors[i] = (DirectReadAccessor<MyClass>)
Delegate.CreateDelegate(
DirectReadAccessor<MyClass>,
null,
directReadAccessorsMInfo[i].MakeGenericMethod(typeArguments)
);
}
}
}
* on open delegate instances .
, MyClass , directReadAccessors, DirectReadAccessor [], InitalizeClass, MyClass, (, ). , , DirectRead, , , . -, emit:
ilGenerator.Emit(OpCodes.Callvirt, invokeMInfo);
invokeMInfo - Invoke DirectReadAccessor :
MethodInfo invokeMInfo = typeof(DirectReadAccessor<MyClass>).GetMethod(
"Invoke",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
new Type[] { typeof(MyClass) },
null
);
, , MyClass, DirectReadAccessor . TypeBuilder MyClass DirectReadAccessor, :
directReadAccessorType = typeof(DirectReadAccessor<>).MakeGenericType(typeBuilder);
GetMethod ( "Invoke",....) directReadAccessorType, , NotSupportedException, Invoke . , :
typeBuilder.CreateType();
, . , Invoke MethodInfo , InitializeClass.
: , , . - ?
, .