在 C# 中,List 对象似乎不能存储在 List 变量中,甚至不能以这种方式显式转换。
List<string> sl = new List<string>();
List<object> ol;
ol = sl;
结果无法隐式转换类型 System.Collections.Generic.List<string>
至 System.Collections.Generic.List<object>
然后……
List<string> sl = new List<string>();
List<object> ol;
ol = (List<object>)sl;
无法转换类型的结果 System.Collections.Generic.List<string>
至 System.Collections.Generic.List<object>
当然,您可以通过将所有内容从字符串列表中拉出并一次将其放回一个来实现,但这是一个相当复杂的解决方案。
最佳答案
这样想,如果你要进行这样的转换,然后将一个 Foo 类型的对象添加到列表中,字符串列表就不再一致了。如果你要迭代第一个引用,你会得到一个类转换异常,因为一旦你命中 Foo 实例,Foo 就无法转换为字符串!
作为旁注,我认为是否可以进行反向转换会更重要:
List<object> ol = new List<object>();
List<string> sl;
sl = (List<string>)ol;
我有一段时间没有使用 C#,所以我不知道这是否合法,但这种转换实际上(可能)有用。在这种情况下,您将从一个更通用的类(对象)转到一个从通用类扩展而来的更具体的类(字符串)。这样,如果您添加到字符串列表,则不会违反对象列表。
有人知道或可以测试这样的转换在 C# 中是否合法吗?
关于c# - 在 C# 中,为什么 List<string> 对象不能存储在 List<object> 变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6557/