相关疑难解决方法(0)

在C#中,为什么List <string>对象不能存储在List <object>变量中

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

List<string> sl = new List<string>();
List<object> ol;
ol = sl;
Run Code Online (Sandbox Code Playgroud)

结果无法隐式转换System.Collections.Generic.List<string>System.Collections.Generic.List<object>

然后...

List<string> sl = new List<string>();
List<object> ol;
ol = (List<object>)sl;
Run Code Online (Sandbox Code Playgroud)

结果无法将类型转换System.Collections.Generic.List<string>System.Collections.Generic.List<object>

当然,您可以通过从字符串列表中提取所有内容并将其一次放回一个来实现,但这是一个相当复杂的解决方案.

.net c# generics covariance type-safety

83
推荐指数
6
解决办法
7万
查看次数

标签 统计

.net ×1

c# ×1

covariance ×1

generics ×1

type-safety ×1