虽然我们可以从基类/接口继承,但为什么我们不能声明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#.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)