gpt4 book ai didi

c# - C#中的继承和容器

转载 作者:行者123 更新时间:2023-11-30 13:32:15 24 4
gpt4 key购买 nike

我在这里用 C# 工作,假设我有:

class A
{}

class B : A
{}

List<B> myList;

我想在部分代码中将此 myList 转换为 List< A>,但是当我尝试时,出现错误:

List<A> myUpcastedList = (List<A>)myList; //not working

可以吗?如果是,语法是什么?

最佳答案

List<B>无法转换为 List<A> .您必须创建新的 List<A>并用源代码中的项目填充它。您可以为此使用 LINQ to Objects:

var aList= bList.Cast<A>().ToList();

您还应该阅读一些有关协变和逆变的知识,例如在 Eric Lippert’s Blog

关于c# - C#中的继承和容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15282089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com