[编辑:我很抱歉......最初的问题措辞含糊不清,我没有得到我正在寻找的答复]
对于任何继承自类 Y 的类 X,new List<X>() is IEnumerable<Y>
是真的。但是,这不适用于结构:new List<int>() is IEnumerable<ValueType>
是假的。我的问题是:为什么?
这是一个示例程序:
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");
}
}
}
Output:
System.Collections.Generic.List`1[ConsoleApplication1.Program+X] 是 Y 的列表
System.Collections.Generic.List`1[System.String] 是对象列表
System.Collections.Generic.List`1[ConsoleApplication1.Program+Z] 最有可能是 ValueTypes 列表或字符串
System.Collections.Generic.List`1[System.Int32] 很可能是 ValueTypes 列表或字符串
blah 很可能是 ValueTypes 列表或字符串
1 不是列表
那么为什么是new List<int>
not a IEnumerable<ValueType>
?
协方差仅适用于引用类型,不适用于值类型。所以一个List<string>
可分配给IEnumerable<object>
因为string
是一个引用类型,但是List<int>
不可分配给IEnumerable<ValueType>
。详细信息请参见 C# 语言规范第 13.1.3.2 节
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)