为什么名单< 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
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcgaeig
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20