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

编程入门 行业动态 更新时间:2024-10-14 04:23:24
本文介绍了为什么名单< 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;?

本文发布于:2023-11-09 04:26:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571401.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:没有了   名单   类型   LT   GT

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!