views:

157

answers:

2

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

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

Help appreciated.

+2  A: 

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.

Jb Evain
A: 

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