虽然我们可以从基类/接口(interface)继承,为什么我们不能声明一个List<>
使用相同的类/接口(interface)?
interface A
{ }
class B : A
{ }
class C : B
{ }
class Test
{
static void Main(string[] args)
{
A a = new C(); // OK
List<A> listOfA = new List<C>(); // compiler Error
}
}
有办法吗?
最佳答案
实现此功能的方法是遍历列表并强制转换元素。这可以使用 ConvertAll 来完成:
List<A> listOfA = new List<C>().ConvertAll(x => (A)x);
您还可以使用 Linq:
List<A> listOfA = new List<C>().Cast<A>().ToList();
关于c# - 将 List<DerivedClass> 转换为 List<BaseClass>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1817300/