I'm having yet another nasty moment with Reflection.Emit
and type management.
Say, I have a type named MyType
which is defined in the dynamically generated assembly.
Calling MyType.GetMethods()
results in a NotSupportedException
, which has reduced me to writing my own set of wrappers and lookup tables. However, the same is happening when I'm calling GetMethods()
or any other introspecting methods on standard generic types which use my own types as generic arguments:
Tuple<int, string>
=> works fineTuple<int, MyType>
=> exception
I can get the method list from the generic type definition:
typeof(Tuple<int, MyType).GetGenericTypeDefinition().GetMethods()
However, the methods have generic placeholders instead of actual values (like T1
, TResult
etc.) and I don't feel like writing yet another kludge that traces the generic arguments back to their original values.
A sample of code:
var asmName = new AssemblyName("Test");
var access = AssemblyBuilderAccess.Run;
var asm = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, access);
var module = asm.DefineDynamicModule("Test");
var aType = module.DefineType("A");
var tupleType = typeof(Tuple<,>);
var tuple = tupleType.MakeGenericType(new [] { typeof(int), aType });
tuple.GetProperty("Item1"); // <-- here's the error
So the questions are:
- How do I detect if a type is safe to call
GetMethods()
and similar methods on? - How do I get the actual list of methods and their generic argument values, if the type is not safe?
NotSupportedException
- is there nothing in the message? – BresciaGetMethods()
andSystem.Reflection.Emit.TypeBuilderInstantiation.GetMethods(BindingFlags bindingAttr)
inside it. – IndestructibleMethodInfo
s (etc.) because you are still busy building the type, you do in fact have to keep track of the originalMethodBuilder
s (etc.) for use in method invocations and other emitted calls. If you need theMethodInfo
s (etc.) after you've already calledCreateType
, then, as Eric answered, you can invoke those methods on the created type. – XeresA
andB
. TypeB
has a method that usesTuple<int, A>
and needs to gettuple.Item1
out of it. I detect the type oftuple
variable and callGetProperties()
on it. There are noMethodBuilder
s to track since I have not defined this type, but merely instantiated it by applying generic arguments. – Indestructible