What Types should be in the Type array for Type.GetMethod when a parameter is generic?

前端 未结 2 1636
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-24 01:09

If I want to call a generic method through reflection, I can easily use this technique, unless:

  1. The method can only be distinguished from another by its parameters
2条回答
  •  抹茶落季
    2021-01-24 01:44

    I'll give you the full "thing" I use when I have to find a Queryable.Select Method (IQueryable, Expression>) 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.

    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".

    In your specific case:

    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();
    

提交回复
热议问题