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

2023-09-04 03:06:13 作者:今晚不打烊

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