通用的奇怪行为

Ten*_*ere 6 c#

我遇到了泛型的奇怪行为.下面是我用于测试的代码.

public static class Program
{
    public static void Main()
    {
        Type listClassType = typeof(List<int>).GetGenericTypeDefinition();
        Type listInterfaceType = listClassType.GetInterfaces()[0];

        Console.WriteLine(listClassType.GetGenericArguments()[0].DeclaringType);
        Console.WriteLine(listInterfaceType.GetGenericArguments()[0].DeclaringType);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

System.Collections.Generic.List`1[T]
System.Collections.Generic.List`1[T]
Run Code Online (Sandbox Code Playgroud)

我发现第二个Console.WriteLine调用显示一个类而不是一个接口是非常奇怪的,因为我使用泛型类型定义.这是正确的行为吗?

我正在尝试在我的编译器中实现泛型类型推断.假设我有以下代码.

public static class GenericClass
{
    public static void GenericMethod<TMethodParam>(IList<TMethodParam> list) { }
}
Run Code Online (Sandbox Code Playgroud)

我想将此方法称为如下:

GenericClass.GenericMethod(new List<int>());
Run Code Online (Sandbox Code Playgroud)

为了检查推理的可能性,我必须比较方法签名中的类型和传递的参数类型.但是下面的代码返回false.

typeof(GenericClass).GetMethods()[0].GetParameters()[0].ParameterType == listInterfaceType;
Run Code Online (Sandbox Code Playgroud)

我是否应该始终使用Type.GetGenericTypeDefinition进行此类比较?

Eri*_*ert 15

你混淆了两个名为T的不同类型.想想这样:

interface IFoo<TIFOO> { }
class Foo<TFOO> : IFoo<TFOO> {}
Run Code Online (Sandbox Code Playgroud)

好的,通用类型定义Foo<int>什么?那是Foo<TFOO>.

实现Foo<TFOO>接口是什么?那是IFoo<TFOO>.

什么是类型参数Foo<TFOO>?显然TFOO.

宣布 什么类型TFOOFoo<TFOO>宣布它.

什么是类型参数IFoo<TFOO>?显然TFOO,不是 TIFOO.

宣布 什么类型TFOOFoo<TFOO>宣布它. 没有 IFoo<TFOO>. TFOO来自Foo.

合理?