我想通过反射选择正确的通用方法,然后调用它.
通常这很容易.例如
var method = typeof(MyType).GetMethod("TheMethod");
var typedMethod = method.MakeGenericMethod(theTypeToInstantiate);
Run Code Online (Sandbox Code Playgroud)
但是,当方法存在不同的泛型重载时,问题就开始了.例如,System.Linq.Queryable类中的静态方法.'Where'方法有两种定义
static IQueryable<T> Where(this IQueryable<T> source, Expression<Func<T,bool>> predicate)
static IQueryable<T> Where(this IQueryable<T> source, Expression<Func<T,int,bool>> predicate)
Run Code Online (Sandbox Code Playgroud)
这说明GetMethod无法正常工作,因为它无法让两者黯然失色.因此,我想选择正确的.
到目前为止,我经常只采取第一种或第二种方法,这取决于我的需要.像这样:
var method = typeof (Queryable).GetMethods().First(m => m.Name == "Where");
var typedMethod = method.MakeGenericMethod(theTypeToInstantiate);
Run Code Online (Sandbox Code Playgroud)
但是我对此并不满意,因为我做了一个很大的假设,即第一种方法是正确的.我宁愿通过参数类型找到正确的方法.但我无法弄清楚如何.
我尝试传递'类型',但它没有用.
var method = typeof (Queryable).GetMethod(
"Where", BindingFlags.Static,
null,
new Type[] {typeof (IQueryable<T>), typeof (Expression<Func<T, bool>>)},
null);
Run Code Online (Sandbox Code Playgroud)
所以有人知道如何通过反射找到'正确'的通用方法.例如,Queryable类的'Where'方法的正确版本?
我有一个相当简单的问题,但在C#中似乎没有解决方案.
我有大约100个Foo类,每个类都实现一个static FromBytes()方法.还有一些泛型类应该使用这些方法FromBytes().但是泛型类不能使用这些static FromBytes()方法,因为它们T.FromBytes(...)是非法的.
我是否遗漏了某些内容或者无法实现此功能?
public class Foo1
{
public static Foo1 FromBytes(byte[] bytes, ref int index)
{
// build Foo1 instance
return new Foo1()
{
Property1 = bytes[index++],
Property2 = bytes[index++],
// [...]
Property10 = bytes[index++]
};
}
public int Property1 { get; set; }
public int Property2 { get; set; }
// [...]
public int Property10 { get; set; }
}
//public class Foo2 { ... }
// …Run Code Online (Sandbox Code Playgroud) 我有MethodInfo一个GenericMethodDefinition.如:CallMethod<T>(T arg, string arg2).GetParameters()方法将为我提供两个ParameterInfo对象,第一个是通用的,第二个不是.如何让ParameterInfo告诉我它是通用的?如果它有约束怎么办?