在C#中,为什么不能一个List<字符串>对象被存储在一个列表与所述;对象>变量 [英] In C#, why can't a List<string> object be stored in a List<object> variable

查看:155
本文介绍了在C#中,为什么不能一个List<字符串>对象被存储在一个列表与所述;对象>变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看来,一个List对象不能存储在C#中的列表变量,甚至不能明确地投的方式。

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&LT;字符串&GT; System.Collections.Generic.List&LT;对象&gt;

然后......

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

导致无法将类型 System.Collections.Generic.List&LT;字符串&GT; System.Collections.Generic.List&LT;对象&gt;

当然,你可以拉出来的一切字符串列表,并把它放回一次做到这一点,但它是一个相当复杂的解决方案。

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类型的对象添加到列表中,字符串列表没有不再是一致的。如果你要遍历第一个参考,你会得到一类转换异常,因为一旦你打美孚情况下,富不能转换成字符串!

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&LT;字符串&GT;对象被存储在一个列表与所述;对象&gt;变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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