How to find an overloaded method by reflection
Asked Answered
P

2

5

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.

Perverse answered 5/5, 2012 at 18:44 Comment(0)
H
6

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();
Hans answered 5/5, 2012 at 19:9 Comment(2)
Sorry, another point. How to detect if a type follows a generic type's constraints?Perverse
take a peek with the debugger at typeof(SomeType<>).GetGenericArguments().First().GetGenericParameterConstraints() and see the Type.IsAssignableFrom method: msdn.microsoft.com/en-us/library/… I think combining them will get you what you wantHans
H
0

Look into the MethodInfo Members: http://msdn.microsoft.com/en-US/library/system.reflection.methodinfo_members(v=vs.80).aspx

There are helper properties for IsGenericMethodDefinition and GetParameters. Both could help you figure out what function is what.

Higley answered 5/5, 2012 at 18:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.