简体   繁体   中英

How do I get the Type of a generic parameter for a given method

Ok, here's the problem. I have a problem when comparing the return type of two different methods.

The first method is hard coded to a specific generic type, so when you get information on the method return type, it includes the type. Here's what I mean.

public Task<Message> GetMessage(long id)
{
    ...
    return await getEntityFromDbById<Message>(id); //generic type is hard coded to type Message
}

If you get the method info this.GetType().GetTypeInfo().GetDeclaredMethod("GetMessage").ReturnType.ToString() , and look at it's return type, this is what you get

System.Threading.Tasks.Task`1[Core.Models.Message]

Now, my second method is generic and looks like this.

public Task<T> GetEntityById<T>(long id) where T : class, IEntity
{
    ...
    return await getEntityFromDbById<T>(id); // generic type is passed in
}

Now if you get the ReturnType information for this method you get

System.Threading.Tasks.Task`1[T]

What I'm trying to do at runtime, is get the type information of T and compare it to the other method using only MethodInfo types. How can this be done?

public bool compareMethods(MethodInfo method1, MethodInfo method2)
{
    ...
    //Won't work because one method has a generic return type. 
    //How do you detect and compare?    
    return method1.ReturnType == method2.ReturnType; 
}

Given a type reference, you can access the type of information of the references generic type parameters by using the method GetGenericArguments() which will return an array of type references for the generic parameters.

The same method is defined on MethodInfo . Since you only have a single generic parameter in your declaration, you can actually just write:

public bool compareMethods(MethodInfo method1, MethodInfo method2)
{
    return method1.GetGenericArguments()[0] == method2.GetGenericArguments()[0]; 
}

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