在 C# 中,为什么不能使用 List<string>object 存储在 List<object> 中.多变的 [英] In C#, why can&#39;t a List&lt;string&gt; object be stored in a List&lt;object&gt; variable

查看:45
本文介绍了在 C# 中,为什么不能使用 List<string>object 存储在 List<object> 中.多变的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎 List 对象不能存储在 C# 中的 List 变量中,甚至不能以这种方式显式转换.

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;

导致无法将类型System.Collections.Generic.List 隐式转换为System.Collections.Generic.List

results in Cannot implicitly convert type System.Collections.Generic.List<string> to System.Collections.Generic.List<object>

然后……

List<string> sl = new List<string>();
List<object> ol;
ol = (List<object>)sl;

导致无法将类型 System.Collections.Generic.List 转换为 System.Collections.Generic.List

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.

推荐答案

这样想,如果你做这样的转换,然后将一个 Foo 类型的对象添加到列表中,字符串列表是没有的更一致.如果你要迭代第一个引用,你会得到一个类转换异常,因为一旦你命中 Foo 实例,Foo 就无法转换为字符串!

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;

我有一段时间没有使用 C#,所以我不知道这是否合法,但这种类型的转换实际上(可能)有用.在这种情况下,您将从更通用的类(对象)转换为从通用类扩展的更具体的类(字符串).这样,如果添加到字符串列表中,就不会违反对象列表.

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.

有人知道或可以测试这样的强制转换在 C# 中是否合法吗?

Does anybody know or can test if such a cast is legal in C#?

这篇关于在 C# 中,为什么不能使用 List<string>object 存储在 List<object> 中.多变的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆