Reflection - Navigate a non-generic method from a generic type definition to a concrete one

Let's say I have a class as follow:

    class A<T>
    {
        public void Method()
        {
        }
    }

So the class is generic but its methods aren't.

I can find the method, say:

var m = typeof(A<int>).GetGenericTypeDefinition().GetMethod("Method");

Now I would like to navigate from this 'm' (which is really A<T>.Method) to a concrete type, e.g. A<int>.Method.

I would like to do that in a general way, i.e. I don't want to use method name since I might have cases with overloaded number of parameters.

Is there a way to do that or do I have to load the methods with the same names and compare parameters?

Upvotes: 0

Views: 193

Answers (1)

BartoszKP
BartoszKP

Reputation: 35921

You can use the MakeGenericType method, like this:

m.DeclaringType.MakeGenericType(typeof(int))

and then probably GetMethod again if you really want to go this way:

m.DeclaringType.MakeGenericType(typeof(int)).GetMethod("Method");

However, consider Jon Skeet's comment for simpler solution.

Upvotes: 1

Related Questions