相关疑难解决方法(0)

将List <DerivedClass>转换为List <BaseClass>

虽然我们可以从基类/接口继承,但为什么我们不能声明List<> 使用相同的类/接口?

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
    }
}
Run Code Online (Sandbox Code Playgroud)

有办法吗?

c# collections inheritance list covariance

162
推荐指数
7
解决办法
10万
查看次数

标签 统计

c# ×1

collections ×1

covariance ×1

inheritance ×1

list ×1