class Program
{
class Example : List<Type> { }
static void Main(string[] args)
{
var mi = typeof(Example).GetMethod("IndexOf", new Type[] { typeof(Type), typeof(int) });
var realMi = MyFunction(mi);
Console.WriteLine(string.Format("Initial definition: {0}", mi));
Console.WriteLine(string.Format("Base definition: {0}", mi.GetBaseDefinition()));
Console.WriteLine(string.Format("MyFunction Result: {0}", realMi));
var tType1 = typeof(List<>).GetGenericTypeDefinition().GetGenericArguments()[0];
Console.WriteLine(string.Format("Goal Example 1: {0}",
typeof(List<>).GetMethod("IndexOf", new Type[] { tType1, typeof(int) })));
var tType2 = mi.DeclaringType.GetGenericTypeDefinition().GetGenericArguments()[0];
Console.WriteLine(string.Format("Goal Example 2: {0}",
mi.DeclaringType.GetGenericTypeDefinition().GetMethod("IndexOf",
new Type[] { tType2, typeof(int) })));
Console.ReadKey();
}
static MethodInfo MyFunction(MethodInfo mi)
{
// what code should be there???
return mi.DeclaringType.GetGenericTypeDefinition().GetMethod("IndexOf",
mi.GetParameters().Select(p => p.GetType()).ToArray());
}
}
如何从MyFunction获取目标?
控制台输出:
Initial definition: Int32 IndexOf(System.Type, Int32)
Base definition: Int32 IndexOf(System.Type, Int32)
MyFunction Result:
Goal Example 1: Int32 IndexOf(T, Int32)
Goal Example 2: Int32 IndexOf(T, Int32)
答案 0 :(得分:1)
尝试:
static MethodInfo MyFunction(MethodInfo mi) {
Type listT = mi.DeclaringType.GetGenericTypeDefinition();
MethodInfo miListT = (MethodInfo)MethodBase.GetMethodFromHandle(mi.MethodHandle, listT.TypeHandle);
return miListT;
}
你可以使用相同的&#34;技巧&#34;来自List<X1>.IndexOf
→List<Y1>.IndexOf
,List<>.IndexOf
→List<X1>.IndexOf
,List<X1>.IndexOf
→List<>.IndexOf
。