我在Reflection.Emit类型管理方面又遇到了麻烦。
比如说,我有一个名为的类型MyType,它是在动态生成的程序集中定义的。在 a 中调用MyType.GetMethods()结果NotSupportedException,这使我不得不编写自己的一组包装器和查找表。但是,当我在GetMethods()使用我自己的类型作为泛型参数的标准泛型类型上调用或任何其他自省方法时,也会发生同样的情况:
Tuple<int, string>=> 工作正常Tuple<int, MyType>=> 例外
我可以从泛型类型定义中获取方法列表:
typeof(Tuple<int, MyType).GetGenericTypeDefinition().GetMethods()
但是,这些方法具有通用占位符而不是实际值(例如T1等TResult),我不想编写另一个将通用参数追溯到其原始值的 kludge。
代码示例:
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
所以问题是:
- 如何检测类型是否可以安全调用
GetMethods()以及类似的方法? - 如果类型不安全,如何获取方法的实际列表及其通用参数值?