In C#, why can#39;t a Listlt;stringgt; object be stored in a Listlt;objectgt; variable(在 C# 中,为什么不能 Listlt;stringgt;对象被存储在一个列表lt;对象gt;多变的)
问题描述
It seems that a List object cannot be stored in a List variable in C#, and can't even be explicitly cast that way.
List<string> sl = new List<string>();
List<object> ol;
ol = sl;
results in Cannot implicitly convert type System.Collections.Generic.List<string>
to System.Collections.Generic.List<object>
And then...
List<string> sl = new List<string>();
List<object> ol;
ol = (List<object>)sl;
results in Cannot convert type System.Collections.Generic.List<string>
to System.Collections.Generic.List<object>
Of course, you can do it by pulling everything out of the string list and putting it back in one at a time, but it is a rather convoluted solution.
Think of it this way, if you were to do such a cast, and then add an object of type Foo to the list, the list of strings is no longer consistent. If you were to iterate the first reference, you would get a class cast exception because once you hit the Foo instance, the Foo could not be converted to string!
As a side note, I think it would be more significant whether or not you can do the reverse cast:
List<object> ol = new List<object>();
List<string> sl;
sl = (List<string>)ol;
I haven't used C# in a while, so I don't know if that is legal, but that sort of cast is actually (potentially) useful. In this case, you are going from a more general class (object) to a more specific class (string) that extends from the general one. In this way, if you add to the list of strings, you are not violating the list of objects.
Does anybody know or can test if such a cast is legal in C#?
这篇关于在 C# 中,为什么不能 List<string>对象被存储在一个列表<对象>多变的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C# 中,为什么不能 List<string>对象被存储在一个列表<对象>多变的
基础教程推荐
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01