Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find an overloaded method by reflection

This is a question associated with another question I asked before. I have an overloaded method:

public void Add<T>(SomeType<T> some) { }

public void Add<T>(AnotherType<T> another) { }

How can I find each method by reflection? e.g. How can I get the Add<T>(SomeType<T> some) method by reflection? Can you help me please? Thanks in advance.

like image 312
amiry jd Avatar asked May 05 '12 18:05

amiry jd


1 Answers

The trick here is describing that you want the parameter to be SomeType<T>, where T is the generic type of the Add method.

Other than that, it's just about using standard reflection, like CastroXXL suggested in his answer.

Here's how I did it:

var theMethodISeek = typeof(MyClass).GetMethods()
    .Where(m => m.Name == "Add" && m.IsGenericMethodDefinition)
    .Where(m =>
            {
                // the generic T type
                var typeT = m.GetGenericArguments()[0];

                // SomeType<T>
                var someTypeOfT = 
                    typeof(SomeType<>).MakeGenericType(new[] { typeT });

                return m.GetParameters().First().ParameterType == someTypeOfT;
            })
    .First();
like image 186
Cristian Lupascu Avatar answered Sep 20 '22 21:09

Cristian Lupascu