加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 通用的奇怪行为

发布时间:2020-12-15 18:08:17 所属栏目:百科 来源:网络整理
导读:我遇到了泛型的奇怪行为.下面是我用于测试的代码. public static class Program{ public static void Main() { Type listClassType = typeof(Listint).GetGenericTypeDefinition(); Type listInterfaceType = listClassType.GetInterfaces()[0]; Console.Wri
我遇到了泛型的奇怪行为.下面是我用于测试的代码.
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);
    }
}

输出:

System.Collections.Generic.List`1[T]
System.Collections.Generic.List`1[T]

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

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

public static class GenericClass
{
    public static void GenericMethod<TMethodParam>(IList<TMethodParam> list) { }
}

我想将此方法称为如下:

GenericClass.GenericMethod(new List<int>());

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

typeof(GenericClass).GetMethods()[0].GetParameters()[0].ParameterType == listInterfaceType;

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

解决方法

你混淆了两个名为T的不同类型.想想这样:
interface IFoo<TIFOO> { }
class Foo<TFOO> : IFoo<TFOO> {}

好的,Foo< int&gt ;?的泛型类型定义是什么?那是Foo< TFOO>.

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

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

宣告TFOO是什么类型的? FOO< TFOO>宣布它.

IFoo< TFOO&gt ;?的类型参数是什么?显然是TFOO,而不是TIFOO. 宣告TFOO是什么类型的? FOO< TFOO>宣布它.不是IFoo< TFOO>. TFOO来自Foo.

合理?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读