How to get MethodInfo of a generic method?

2019-08-02 06:16发布

I am trying to get a MethodInfo object for the method:

Any<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>)

The problem I'm having is working out how you specify the type parameter for the Func<TSource, Boolean> bit...

MethodInfo method = typeof(Enumerable).GetMethod("Any", new[] { typeof(Func<what goes here?, Boolean>) });

Help appreciated.

2条回答
成全新的幸福
2楼-- · 2019-08-02 06:44

You can create an extension method that does the work of retrieving all of the methods and filtering them in order to return the desired generic method.

public static class TypeExtensions
{
    private class SimpleTypeComparer : IEqualityComparer<Type>
    {
        public bool Equals(Type x, Type y)
        {
            return x.Assembly == y.Assembly &&
                x.Namespace == y.Namespace &&
                x.Name == y.Name;
        }

        public int GetHashCode(Type obj)
        {
            throw new NotImplementedException();
        }
    }

    public static MethodInfo GetGenericMethod(this Type type, string name, Type[] parameterTypes)
    {
        var methods = type.GetMethods();
        foreach (var method in methods.Where(m => m.Name == name))
        {
            var methodParameterTypes = method.GetParameters().Select(p => p.ParameterType).ToArray();

            if (methodParameterTypes.SequenceEqual(parameterTypes, new SimpleTypeComparer()))
            {
                return method;
            }
        }

        return null;
    }
}

Using the extension method above, you can write code similar to what you had intended:

MethodInfo method = typeof(Enumerable).GetGenericMethod("Any", new[] { typeof(IEnumerable<>), typeof(Func<,>) });
查看更多
何必那么认真
3楼-- · 2019-08-02 06:56

There's no way of getting it in a single call, as you would need to make a generic type constructed of the generic parameter of the method (TSource in this case). And as it's specific to the method, you would need to get the method to get it and build the generic Func type. Chicken and egg issue heh?

What you can do though is to get all the Any methods defined on Enumerable, and iterate over those to get the one you want.

查看更多
登录 后发表回答