vendredi 25 mars 2016

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; 
}





Aucun commentaire:

Enregistrer un commentaire