一篇學會 C# 集合類型
對于許多應用程序,你會想要創(chuàng)建和管理相關對象的組。有兩種方法對對象進行分組:通過創(chuàng)建對象的數(shù)組,以及通過創(chuàng)建對象的集合。
數(shù)組最適用于創(chuàng)建和使用固定數(shù)量的強類型化對象。
集合提供更靈活的方式來使用對象組。與數(shù)組不同,你使用的對象組隨著應用程序更改的需要動態(tài)地放大和縮小。對于某些集合,你可以為放入集合中的任何對象分配一個密鑰,這樣你便可以使用該密鑰快速檢索此對象。
集合是一個類,因此必須在向該集合添加元素之前,聲明類的實例。
如果集合中只包含一種數(shù)據(jù)類型的元素,則可以使用 System.Collections.Generic 命名空間中的一個類。泛型集合強制類型安全,因此無法向其添加任何其他數(shù)據(jù)類型。當你從泛型集合檢索元素時,你無需確定其數(shù)據(jù)類型或?qū)ζ溥M行轉(zhuǎn)換。
創(chuàng)建字符串列表,并通過使用 foreach 語句循環(huán)訪問字符串。
- // Create a list of strings.
- var salmons = new List<string>();
- salmons.Add("chinook");
- salmons.Add("coho");
- salmons.Add("pink");
- salmons.Add("sockeye");
- // Iterate through the list.
- foreach (var salmon in salmons)
- {
- Console.Write(salmon + " ");
- }
- // Output: chinook coho pink sockeye
如果集合中的內(nèi)容是事先已知的,則可以使用集合初始值設定項來初始化集合。
- // Create a list of strings by using a
- // collection initializer.
- var salmons = new List<string> { "chinook", "coho", "pink", "sockeye" };
- // Iterate through the list.
- foreach (var salmon in salmons)
- {
- Console.Write(salmon + " ");
- }
- // Output: chinook coho pink sockeye
可以使用 for 語句,而不是 foreach 語句來循環(huán)訪問集合。通過按索引位置訪問集合元素實現(xiàn)此目的。元素的索引開始于 0,結(jié)束于元素計數(shù)減 1。
以下示例通過使用 for 而不是 foreach 循環(huán)訪問集合中的元素。
- // Create a list of strings by using a
- // collection initializer.
- var salmons = new List<string> { "chinook", "coho", "pink", "sockeye" };
- for (var index = 0; index < salmons.Count; index++)
- {
- Console.Write(salmons[index] + " ");
- }
- // Output: chinook coho pink sockeye
對于 List中的元素類型,還可以定義自己的類。在下面的示例中,由 List使用的 Galaxy 類在代碼中定義。
- private static void IterateThroughList()
- {
- var theGalaxies = new List<Galaxy>
- {
- new Galaxy() { Name="Tadpole", MegaLightYears=400},
- new Galaxy() { Name="Pinwheel", MegaLightYears=25},
- new Galaxy() { Name="Milky Way", MegaLightYears=0},
- new Galaxy() { Name="Andromeda", MegaLightYears=3}
- };
- foreach (Galaxy theGalaxy in theGalaxies)
- {
- Console.WriteLine(theGalaxy.Name + " " + theGalaxy.MegaLightYears);
- }
- // Output:
- // Tadpole 400
- // Pinwheel 25
- // Milky Way 0
- // Andromeda 3
- }
- public class Galaxy
- {
- public string Name { get; set; }
- public int MegaLightYears { get; set; }
- }