我在使用反射来区分泛型类上的非泛型和泛型方法时遇到了一些麻烦。这是我正在使用的测试用例:
public class Foo<T>
{
public string Bar( T value ) { return "Called Bar(T)"; }
public string Bar( int value ) { return "Called Bar(int)"; }
public static void CallBar<TR>(Foo<TR> foo)
{
var fooInfo = foo.GetType()
.GetMethods()
.Where(x => !x.IsGenericMethod && // doesn't filter out Bar(T)!
x.Name == "Bar" &&
x.GetParameters().First().ParameterType == typeof(int))
// !Two identical MethodInfo results, how to choose between them?
// Is there a gauranteed canonical ordering? Or is it undefined?
.First();
Console.WriteLine(fooInfo.Invoke(foo, new object[]{ 0 }));
}
}
// prints Bar(T)...
Foo<int>.CallBar( new Foo<int>() );