【发布时间】:2008-08-09 02:32:01
【问题描述】:
似乎 List 对象不能存储在 C# 中的 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>
当然,您可以通过从字符串列表中拉出所有内容并一次将其放回其中来做到这一点,但这是一个相当复杂的解决方案。
【问题讨论】:
-
这将随着 C# 4.0 的变化而改变,因此您可能想要查找协变和逆变。它将以类型安全的方式允许此类事情。
-
John> C#4 不允许这样做。想想 ol.Add(new object());
-
这里由 Jon Skeet 回答:stackoverflow.com/a/2033921/1070906
标签: c# .net generics covariance type-safety