相关疑难解决方法(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#.NET 3.5.我明白了

参数类型'GenericTest.BarkStrategy'不能赋值给参数类型'GenericsTest.IAnimalStrategy'

以下(对于这个问题尽可能简化)代码:

using System.Collections.Generic;

namespace GenericsTest {
    class Program {
        static void Main(string[] args) {
            List<IAnimalStrategy<IAnimal>> strategies = 
                new List<IAnimalStrategy<IAnimal>>();
            strategies.Add(new BarkStrategy());
        }
    }

    interface IAnimal { }
    interface IAnimalStrategy<T> where T : IAnimal { }
    class Dog : IAnimal { }
    class BarkStrategy : IAnimalStrategy<Dog> { }
}
Run Code Online (Sandbox Code Playgroud)

c# generics

4
推荐指数
1
解决办法
2213
查看次数

标签 统计

c# ×2

collections ×1

covariance ×1

generics ×1

inheritance ×1

list ×1