mercredi 4 avril 2018

How to get MethodInfo for a generic method by name and its generic parameters?

I have this interface:

interface IRepository
{
    string GetId<T>(T obj) where T : IDomainObject;
    string GetId<T>(Reference<T> reference) where T : IDomainObject;
}

What exactly IDomainObject and Reference are is not relevant to this question. So assume they are completely empty:

interface IDomainObject
{
    // something
}

class Reference<T> where T : IDomainObject
{
    // something
}

My question is: How do I get the MethodInfo for the GetId<T> method in IRepository that accepts a Reference<T>?


Here's what I've tried:

public MethodInfo GetReferenceAcceptingGetIdMethod()
{
    // We want to return the MethodInfo for the GetId<T> method of IRepository
    // that accepts a Reference<T> argument.

    var repositoryInterfaceType = typeof(IRepository);

    // Look through all methods of IRepository...
    foreach (var m in repositoryInterfaceType.GetMethods())
    {
        // ... to find a candidate method, going by Genericness and Name ...
        if (m.IsGenericMethodDefinition && m.Name == nameof(IRepository.GetId))
        {
            // ... and to narrow it further down by looking at the parameters ...
            var parameters = m.GetParameters();
            if (parameters.Length == 1)
            {
                // ... to check if the one and only parameter is a generic Reference<>.
                var firstParamType = parameters[0].ParameterType;
                var genericReferenceType = typeof(Reference<>);
                if (firstParamType == genericReferenceType)
                {
                    // !!! This if will never be true.
                    // Why?
                    // And what do I have to change the condition into to make it work?
                    return m;
                }
            }
        }
    }

    throw new Exception();
}

It appears that method's parameter type is somehow different from a completely open generic type. I guess and it seems that the type of the method's parameter is somehow linked to the method's generic type parameter.

So how can I get the MethodInfo in such a case?





Aucun commentaire:

Enregistrer un commentaire