简体   繁体   中英

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, eg A<int>.Method .

I would like to do that in a general way, ie 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM