Retrieving the MethodInfo of of the correct overload of a generic method

前端 未结 5 872
误落风尘
误落风尘 2021-01-02 09:25

I have this type that contains two overloads of a generic method. I like to retrieve one of the overloads (with the Func parameter) using reflection. T

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-02 09:34

    I don't think you can do this directly using GetMethod. I suspect you'll have to iterate over all the methods called Bar, then:

    • Check that the method has one type parameter
    • Check that the method has one normal parameter
    • Use the type parameter to make a Func (with typeof(Func<>).MakeGenericType) and check that the parameter type matches that.

    LINQ is good for this sort of thing. Complete sample:

    using System;
    using System.Reflection;
    using System.Linq;
    
    public class Foo
    {
        public void Bar(Func f) { }
        public void Bar(Action a) { }
    }
    
    class Test
    {
        static void Main()
        {
            var methods = from method in typeof(Foo).GetMethods()
                          where method.Name == "Bar"
                          let typeArgs = method.GetGenericArguments()
                          where typeArgs.Length == 1
                          let parameters = method.GetParameters()
                          where parameters.Length == 1
                          where parameters[0].ParameterType == 
                                typeof(Func<>).MakeGenericType(typeArgs[0])
                          select method;
    
            Console.WriteLine("Matching methods...");
            foreach (var method in methods)
            {
                Console.WriteLine(method);
            }
        }
    }
    

    Basically generics and reflection are really nasty in combination, I'm afraid :(

提交回复
热议问题