Why GetMethods () of a Parameterized Generic Interface Returns the Unparameterized MethodInfo

Given these interfaces:

public interface IGenericBase<T>
{
    T MyMethod<T>(T arg1);
}

public interface IGenericDescendant : IGenericBase<int>
{
}

Using the type IGenericDescendant, I get a set of interfaces through GetInterfaces (). As expected, this returns a "permitted" (parameterized) type: IGenericBase`1 with T allowed for Int32. Then I call GetMethods on the specified interface type, expecting to get a similarly permitted version of MyMethod, but instead I get a generic version with T as an argument of an unresolved type.

var type = typeof(IGenericDescendant);    
foreach (var super in type.GetInterfaces())
{
    foreach (var member in super.GetMethods())
    {
        yield return member;  // Get MyMethod<T> not MyMethod<Int32>
    }
}

According to Microsoft documentation , this is the wrong behavior for GetMethods ():

If the current T: System.Type represents the constructed generic type, this method returns MethodInfo objects with type parameters replaced by the corresponding type arguments

, , , , .

, MakeGenericType() , , , , . , . , - .

+4
1

MyMethod - , . - , . :

IGenericDescendant x = new SomeImplementation();
x.MyMethod<string>("abc"); // method is still generic

IGenericBase<int> y = new SomeOtherImplementation();
y.MyMethod<string>("abc"); // still can do that

,

public interface IGenericBase<T>
{
    T MyMethod(T arg1);
}
+3

Source: https://habr.com/ru/post/1533636/


All Articles