C# 当参数为泛型时,Type.GetMethod的类型数组中应该包含哪些类型?
如果我想通过反射调用通用方法,我可以很容易地使用该技术,除非:C# 当参数为泛型时,Type.GetMethod的类型数组中应该包含哪些类型?,c#,generics,reflection,C#,Generics,Reflection,如果我想通过反射调用通用方法,我可以很容易地使用该技术,除非: 该方法只能通过其参数与其他方法进行区分 该方法有一个参数,其类型是该方法的类型参数之一 调用Type.GetMethod(string,Type[])时,如何在Type[]数组中指定泛型参数 例如: public class Example { //This is the one I want to call. public void DoSomething<T>(T t) { ... } pu
Type.GetMethod(string,Type[])
时,如何在Type[]数组中指定泛型参数
例如:
public class Example
{
//This is the one I want to call.
public void DoSomething<T>(T t) { ... }
public void DoSomething(Foo foo) { ... }
public void CallDoSomething(Type type, object value)
{
MethodInfo method = typeof(Example)
.GetMethod("DoSomething", new Type[] {/* what do i put here? */ });
MethodInfo generic = method.MakeGenericMethod(type);
generic.Invoke(this, value);
}
公共类示例
{
//这就是我想打电话给的人。
公共无效剂量(T){…}
公共无效的DoSomething(Foo Foo){…}
public void CallDoSomething(类型、对象值)
{
MethodInfo方法=类型(示例)
.GetMethod(“DoSomething”,新类型[]{/*我在这里放什么?*/});
MethodInfo generic=method.MakeGenericMethod(类型);
generic.Invoke(这个,值);
}
您可以这样做:
MethodInfo method = typeof(Example)
.GetMethods().First(mi => mi.Name == "DoSomething" && mi.IsGenericMethod);
根据您有多少方法重载,您可能需要使谓词更具体。我将为您提供我在查找方法时使用的完整“东西”…它非常复杂,几乎可以检查所有:
MethodInfo selectMethod = (from x in typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public)
where x.Name == "Select" && x.IsGenericMethod
let pars = x.GetParameters()
where pars.Length == 2
let args = x.GetGenericArguments()
where args.Length == 2 &&
pars[0].ParameterType == typeof(IQueryable<>).MakeGenericType(args[0]) &&
pars[1].ParameterType == typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(args))
select x).Single();
如果您向我们提供更多有关您试图实现的目标的信息,这将非常有帮助。您很可能希望调用GetMethods
,然后从中找到正确的方法。@JonSkeet可能会有帮助。我将添加一个示例。
MethodInfo method = (from x in typeof(Example).GetMethods(BindingFlags.Instance | BindingFlags.Public)
where x.Name == "DoSomething" && x.IsGenericMethod
let pars = x.GetParameters()
where pars.Length == 1
let args = x.GetGenericArguments()
where args.Length == 1 &&
pars[0].ParameterType == args[0]
select x).Single();