我有这两个类
public class A {}
public class B : A {}
并且从 A
类到 B
类的转换工作正常。
B testB1 = new B();
A testA1 = testB1;
B testB2 = (B)testA1; //this works
但是:为什么这个转换不起作用?
List<B> testB1List = new List<B>();
List<A> testA1List = ((IEnumerable<A>)testB1List).ToList();
List<B> testB2List = ((IEnumerable<B>)testA1List).ToList(); //not working
解决方法是:
List<B> testB1List = new List<B>();
List<A> testA1List = ((IEnumerable<A>)testB1List).ToList();
List<B> testB2List = testA1List.Cast<B>().ToList();
但为什么会这样呢?
最佳答案
好吧,Cast 扩展方法将列表的每个成员转换为指定的类型,因此在您的示例中,它可以被分配为 List<B>
因为所有列表成员都已转换为 B。
但在第一个示例中,您正在转换 IEnumerable 本身,而不是列表的成员:
(IEnumerable<B>)testA1List
所以它失败了,因为它试图转换 List<A>
至 IEnumerable<B>
.
关于c# - 将通用列表形式 DerivedClass 转换为 BaseClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60915572/