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中文網其他相關文章!