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
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:
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 :(