Passing the correct type parameter to MethodInfo G

2019-05-28 02:21发布

问题:

I know I could use a technique like in this question to get my method.

E.g

MethodInfo firstMethod = typeof(Enumerable)
    .GetMethods(BindingFlags.Public | BindingFlags.Static)
    .First(m => m.Name == "FirstOrDefault" && m.GetParameters().Length == 1)

I want to shortcut that process though.

I'm looking for Enumerable.FirstOrDefault Method (IEnumerable)

I've tried both

// I'm just using string just as an example.
var enumerableType = typeof(IEnumerable<>).MakeGenericType(typeof(string));
MethodInfo firstMethod = typeof(Enumerable)
.GetMethod("FirstOrDefault", new Type[] { enumerableType });

and

MethodInfo firstMethod = typeof(Enumerable)
.GetMethod("FirstOrDefault", Type.EmptyTypes);

But both return null.

What would be the correct approach?

回答1:

Unfortunutely there is no easy way to get the correct overload when the parameter type is generic. You can do it using LINQ manually:

typeof(Enumerable)
  .GetMethods(BindingFlags.Public | BindingFlags.Static)
  .First(x => x.Name == "FirstOrDefault" &&
              x.GetParameters().Length == 1 &&
              x.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == typeof(IEnumerable<>));

In this case since the FirstOrDefault has only one overload that takes one parameter you can remove the last condition.But it is necessary when there are overloads that takes same number of parameters of different types.



标签: c# reflection