为什么名单< INT>没有了IEnumerable<值类型>? [英] Why is List<int> not IEnumerable<ValueType>?

查看:139
本文介绍了为什么名单< INT>没有了IEnumerable<值类型>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于任何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;

推荐答案

协方差仅适用于引用类型,而不是值类型。因此,一个名单,其中,串&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

这篇关于为什么名单&LT; INT&GT;没有了IEnumerable&LT;值类型&GT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆