• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

为什么名单< INT>没有了IEnumerable<值类型>

用户头像
it1352
帮助1

问题说明

对于任何X类继承自类Y,新名单,其中,X>()为IEnumerable的< Y> 是真实的。但是,这并不持有的结构:新名单,其中,INT>()为IEnumerable的<值类型> 是假的。我的问题是:为什么?

For any class X that inherits from class Y, new List<X>() is IEnumerable<Y> is true. However, this doesn't hold for structs: new List<int>() is IEnumerable<ValueType> is false. My question is: Why?

下面是一个简单的程序:

Here is a sample program:

class Program
{
    class Y { }
    class X : Y { }
    struct Z { }

    static void Main(string[] args)
    {
        Test(new List<X>());
        Test(new List<string>());
        Test(new List<Z>());
        Test(new List<int>());
        Test("blah");
        Test(1);
        Console.ReadLine();
    }

    static void Test(object o)
    {
        if (o is IEnumerable<Y>)
        {
            Console.WriteLine(o   " is a list of Ys");
        }
        else if (o is IEnumerable<ValueType>)
        {
            Console.WriteLine(o   " is a list of ValueTypes");
        }
        else if (o is IEnumerable<object>)
        {
            Console.WriteLine(o   " is a list of objects");
        }
        else if (o is System.Collections.IEnumerable)
        {
            Console.WriteLine(o   " is most likely a list of ValueTypes or a string");
        }
        else
        {
            Console.WriteLine(o   " is not a list");
        }

    }
}

输出:

System.Collections.Generic.List`1 [ConsoleApplication1.Program X]是伊苏名单

System.Collections.Generic.List`1[ConsoleApplication1.Program X] is a list of Ys

System.Collections.Generic.List`1 [System.String]为对象的列表

System.Collections.Generic.List`1[System.String] is a list of objects

System.Collections.Generic.List`1 [ConsoleApplication1.Program Z]是最有可能的值类型的列表或字符串

System.Collections.Generic.List`1[ConsoleApplication1.Program Z] is most likely a list of ValueTypes or a string

System.Collections.Generic.List`1 [System.Int32的]是最有可能的值类型或列表的字符串

System.Collections.Generic.List`1[System.Int32] is most likely a list of ValueTypes or a string

等等是最有可能的值类型的列表或字符串

blah is most likely a list of ValueTypes or a string

1是不是列表

那么,为什么新名单,其中,INT&GT; 不是的IEnumerable&LT;值类型&GT;

正确答案

#1

协方差仅适用于引用类型,而不是值类型。因此,一个名单,其中,串&GT; 是分配给的IEnumerable&LT;对象&gt; ,因为字符串是引用类型,但名单,其中,INT&GT; 不是分配给的IEnumerable&LT;值类型&GT; 。见的C#语言规范的细节部分13.1.3.2

Covariance works only for reference types, not for value types. So a List<string> is assignable to an IEnumerable<object> because string is a reference type, but a List<int> is not assignable to an IEnumerable<ValueType>. See section 13.1.3.2 of the C# language specifications for details

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcgaeig
系列文章
更多 icon
同类精品
更多 icon
继续加载