How to find an overloaded method by reflection

This is a question related to 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? for example How can I get a method Add<T>(SomeType<T> some)by reflection? could you help me? Thanks in advance.

+5
source share
2 answers

The trick here describes that you want the parameter to SomeType<T>be where Tis the general type of method Add.

Other than that, it just uses standard reflection, as CastroXXL said in its answer.

Here is 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();
+6
source
0

All Articles