How to get MethodInfo of a generic method?

杀马特。学长 韩版系。学妹 提交于 2019-12-11 07:49:59

问题


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.


回答1:


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.




回答2:


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<,>) });


来源:https://stackoverflow.com/questions/326136/how-to-get-methodinfo-of-a-generic-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!