似乎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>
当然,您可以通过从字符串列表中提取所有内容并将其一次放回一个来实现,但这是一个相当复杂的解决方案.
让我们假设我们有两个类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>
但是在每个帖子中,答案都集中在特定的类/数据结构中,并使这个特定的代码工作,而不是为什么它一般不可能?