请看以下示例(部分取自MSDN博客):
class Animal { }
class Giraffe : Animal { }
static void Main(string[] args)
{
// Array assignment works, but...
Animal[] animals = new Giraffe[10];
// implicit...
List<Animal> animalsList = new List<Giraffe>();
// ...and explicit casting fails
List<Animal> animalsList2 = (List<Animal>) new List<Giraffe>();
}
Run Code Online (Sandbox Code Playgroud)
这是一个协方差问题吗?这将在未来的C#版本中得到支持吗?是否有任何聪明的解决方法(仅使用.NET 2.0)?
我想要一个Covariant集合,其项目可以通过索引检索.IEnumerable是我所知道的唯一.net集合,它是Covariant,但它没有这个索引支持.
具体来说,我想这样做:
List<Dog> dogs = new List<Dog>();
IEnumerable<Animal> animals = dogs;
IList<Animal> animalList = dogs; // This line does not compile
Run Code Online (Sandbox Code Playgroud)
现在,我知道为什么这是一个问题.List实现ICollection具有Add方法.通过向上投射IList动物,它将允许后续代码添加"真实" List<Dog>集合中不允许的任何类型的动物.
那么有人知道一个支持索引查找的集合也是协变的吗?我想不创造自己的.
是否有可能投下List<Subclass>到List<Superclass>在C#4.0?
这些方面的东西:
class joe : human {}
List<joe> joes = GetJoes();
List<human> humanJoes = joes;
Run Code Online (Sandbox Code Playgroud)
这不是协方差的意思吗?
如果你能做到:
human h = joe1 as human;
Run Code Online (Sandbox Code Playgroud)
你为什么不能这样做
List<human> humans = joes as List<human>;
Run Code Online (Sandbox Code Playgroud)
因为那个项目已经被贬低了,所以做人类[0]是不合法的,每个人都会很高兴.现在唯一的选择是创建一个新的List
刚发现这个:
Func<List<object>> foo = () => new List<object>();
List<string> s = (List<string>)foo();
IList<string> s1 = (IList<string>)foo();
Run Code Online (Sandbox Code Playgroud)
编译器抱怨转换为List(有意义),但没有提及IList.让我想知道为什么会这样?