zl程序教程

您现在的位置是:首页 >  Java

当前栏目

一篇学会 C# 集合类型

2023-04-18 15:42:56 时间

 对于许多应用程序,你会想要创建和管理相关对象的组。有两种方法对对象进行分组:通过创建对象的数组,以及通过创建对象的集合。

数组最适用于创建和使用固定数量的强类型化对象。

集合提供更灵活的方式来使用对象组。与数组不同,你使用的对象组随着应用程序更改的需要动态地放大和缩小。对于某些集合,你可以为放入集合中的任何对象分配一个密钥,这样你便可以使用该密钥快速检索此对象。

集合是一个类,因此必须在向该集合添加元素之前,声明类的实例。

如果集合中只包含一种数据类型的元素,则可以使用 System.Collections.Generic 命名空间中的一个类。泛型集合强制类型安全,因此无法向其添加任何其他数据类型。当你从泛型集合检索元素时,你无需确定其数据类型或对其进行转换。

创建字符串列表,并通过使用 foreach 语句循环访问字符串。

  1. // Create a list of strings. 
  2. var salmons = new List<string>(); 
  3. salmons.Add("chinook"); 
  4. salmons.Add("coho"); 
  5. salmons.Add("pink"); 
  6. salmons.Add("sockeye"); 
  7.  
  8. // Iterate through the list. 
  9. foreach (var salmon in salmons) 
  10.     Console.Write(salmon + " "); 
  11. // Output: chinook coho pink sockeye 

如果集合中的内容是事先已知的,则可以使用集合初始值设定项来初始化集合。

  1. // Create a list of strings by using a 
  2. // collection initializer. 
  3. var salmons = new List<string> { "chinook""coho""pink""sockeye" }; 
  4.  
  5. // Iterate through the list. 
  6. foreach (var salmon in salmons) 
  7.     Console.Write(salmon + " "); 
  8. // Output: chinook coho pink sockeye 

可以使用 for 语句,而不是 foreach 语句来循环访问集合。通过按索引位置访问集合元素实现此目的。元素的索引开始于 0,结束于元素计数减 1。

以下示例通过使用 for 而不是 foreach 循环访问集合中的元素。

  1. // Create a list of strings by using a 
  2. // collection initializer. 
  3. var salmons = new List<string> { "chinook""coho""pink""sockeye" }; 
  4.  
  5. for (var index = 0; index < salmons.Countindex++) 
  6.     Console.Write(salmons[index] + " "); 
  7. // Output: chinook coho pink sockeye 

对于 List中的元素类型,还可以定义自己的类。在下面的示例中,由 List使用的 Galaxy 类在代码中定义。

  1. private static void IterateThroughList() 
  2.     var theGalaxies = new List<Galaxy> 
  3.         { 
  4.             new Galaxy() { Name="Tadpole", MegaLightYears=400}, 
  5.             new Galaxy() { Name="Pinwheel", MegaLightYears=25}, 
  6.             new Galaxy() { Name="Milky Way", MegaLightYears=0}, 
  7.             new Galaxy() { Name="Andromeda", MegaLightYears=3} 
  8.         }; 
  9.  
  10.     foreach (Galaxy theGalaxy in theGalaxies) 
  11.     { 
  12.         Console.WriteLine(theGalaxy.Name + "  " + theGalaxy.MegaLightYears); 
  13.     } 
  14.  
  15.     // Output
  16.     //  Tadpole  400 
  17.     //  Pinwheel  25 
  18.     //  Milky Way  0 
  19.     //  Andromeda  3 
  20.  
  21. public class Galaxy 
  22.     public string Name { get; set; } 
  23.     public int MegaLightYears { get; set; }