相关疑难解决方法(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万
查看次数

为什么派生类的泛型会产生非派生类?

让我们假设我们有两个类A,B其中B来自A.

class A
{
}

class B : A
{
}

class C<T>
{
}
Run Code Online (Sandbox Code Playgroud)

现在,C<B> 不获得C<A>.

这让我有点困惑,因为我强调我用A做的"一切",我可以用B做.我确信我错过了一些东西,因为它似乎与OOP的基础相矛盾.

那有什么具体的理由和榜样吗?

编辑:

我读过许多类似的帖子: 在C#中,为什么List <string>对象不能存储在List <object>变量中

当值类型可以相互转换时,为什么我不能将一个值类型的字典转换为另一个值类型的字典?

从IEnumerable <Object>转换为IEnumerable <string>

但是在每个帖子中,答案都集中在特定的类/数据结构中,并使这个特定的代码工作,而不是为什么它一般不可能?

c# oop generics polymorphism

1
推荐指数
1
解决办法
303
查看次数

标签 统计

c# ×2

generics ×2

.net ×1

covariance ×1

oop ×1

polymorphism ×1

type-safety ×1