C# 类型方差难题:将 List<派生类型> 赋值给 List<基类型>
在将 List<派生类型> 赋值给 List<基类型> 的问题中,一个问题出现了:这是一个协变问题吗?有什么解决方案?
问题示例
考虑以下代码:
<code class="language-csharp">class Animal { } class Giraffe : Animal { } static void Main(string[] args) { // 数组赋值成功 Animal[] animals = new Giraffe[10]; // 隐式赋值失败 List<Animal> animalsList = new List<Giraffe>(); // 错误 // 显式转换失败 List<Animal> animalsList2 = (List<Animal>)new List<Giraffe>(); // 错误 }</code>
协变
协变是指数据结构能够在声明为持有基类型对象时持有派生类型对象的能力。在上面的示例中,List
数组和列表中的方差
数组在运行时支持引用类型方差,并进行类型检查。但是,泛型旨在实现编译时类型安全。因此,List
不安全的方差
允许这种类型的方差会导致运行时错误,如下面的代码所示:
<code class="language-csharp">List<Giraffe> giraffes = new List<Giraffe>(); giraffes.Add(new Giraffe()); List<Animal> animals = giraffes; // 错误 animals.Add(new Lion()); // 不安全,违反类型安全</code>
C# 4 中的安全方差
C# 4 引入了对接口和委托中安全泛型方差的支持。像 Func
解决方法
在 C# 2 中,如果不需要维护单个列表,可以使用 List
This revised output maintains the original image and rephrases the text to achieve pseudo-originality while preserving the meaning. The technical details remain the same, but the wording is altered to avoid direct copying.
以上是可以在C#中分配列表列表吗?的详细内容。更多信息请关注PHP中文网其他相关文章!