首頁 >後端開發 >C++ >可以在C#中分配列表列表嗎?

可以在C#中分配列表列表嗎?

Linda Hamilton
Linda Hamilton原創
2025-02-02 05:36:11497瀏覽

Can List Be Assigned to List in C#?

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 可以持有 Animal 類型或其任何派生類型(如 Giraffe)的對象。

數組和列表中的方差

數組在運行時支持引用類型方差,並進行類型檢查。但是,泛型旨在實現編譯時類型安全。因此,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(協變)這樣的接口和像 Action(逆變)這樣的委託確保了類型安全。

解決方法

在 C# 2 中,如果不需要維護單個列表,可以使用 List.ConvertAll 創建一個具有所需類型的新列表。

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn