当参数为通用参数时,Type.GetMethod的Type数组中应包含哪些Types? [英] What Types should be in the Type array for Type.GetMethod when a parameter is generic?
问题描述
If I want to call a generic method through reflection, I can easily use this technique, unless:
- 该方法只能通过其参数来区分.
- 该方法的参数类型是该方法的类型参数之一.
调用Type.GetMethod(string, Type[])
时如何在Type[]
数组中指定通用参数?
How do I specify a generic parameter in the Type[]
array when calling Type.GetMethod(string, 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);
}
推荐答案
I'll give you the full "thing" I use when I have to find a Queryable.Select<TSource, TResult> Method (IQueryable<TSource>, Expression<Func<TSource, TResult>>)
method... It is quite complex and checks nearly all:
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();
您可以轻松地将其用作模板.
You can easily use it as a template.
请注意,未检查返回类型,因为返回类型没有重载.方法是static
和public
的事实由GetMethods()
检查.我检查参数数量,通用参数数量,参数类型.然后,我使用Single()
确保只有一种方法.这应该是面向未来的:即使Microsoft添加了另一个Queryable.Select
方法,它也将是不同的".
Note that the return type isn't checked, because there is no overload for return types. The fact that the method is static
and public
is checked by the GetMethods()
. I check number of parameters, number of generic arguments, type of parameters. Then I use the Single()
to be sure that there is only one method. This should be future-proof: even if Microsoft added another Queryable.Select
method, it would be "different".
在您的特定情况下:
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();
这篇关于当参数为通用参数时,Type.GetMethod的Type数组中应包含哪些Types?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!