集合(C# 和 Visual Basic)
对于很多应用程序,需要创建和管理相关对象组。 有两种方式可以将对象分组:创建对象数组以及创建对象集合。
数组对于创建和处理固定数量的强类型对象最有用。 有关数组的信息,请参见 数组 (Visual Basic)或 数组(C# 编程指南)。
集合提供一种更灵活的处理对象组的方法。 与数组不同,处理的对象组可根据程序更改的需要动态地增长和收缩。 对于某些集合,您可以为放入该集合的任何对象分配一个“键”,以便使用该键快速检索对象。
集合是类,因此必须声明新集合后,才能向该集合中添加元素。
如果集合包含单一数据类型的元素,可使用 System.Collections.Generic 命名空间中的一个类。 “泛型”集合强制“类型安全”,因此无法向该集合中添加任何其他数据类型。 从泛型集合中检索元素时,不必确定元素的数据类型或转换它。
主题内容
使用简单集合
-
System.Collections.Generic 类
System.Collections.Concurrent 类
System.Collections 类
Visual Basic 集合类
实现键/值对集合
使用 LINQ 访问集合
排序集合
定义自定义集合
迭代器
使用简单集合
本节中的示例使用泛型 List 选件类,允许您一起使用强类型列表对象。
下面的示例生成字符串列表,并通过使用 For Each…Next (Visual Basic) 或 foreach (C#) 语句重复访问字符串。
' Create a list of strings.
Dim salmons As New List(Of String)
salmons.Add("chinook")
salmons.Add("coho")
salmons.Add("pink")
salmons.Add("sockeye")
' Iterate through the list.
For Each salmon As String In salmons
Console.Write(salmon & " ")
Next
'Output: chinook coho pink sockeye
// 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
如果事先知道集合的内容,您可以使用集合初始值初始化该集合。 有关更多信息,请参见集合初始值设定项 (Visual Basic)或对象和集合初始值设定项(C# 编程指南)。
下面的示例与前面的示例相同,除了集合初始值设定项被用于将元素添加到集合中。
' Create a list of strings by using a
' collection initializer.
Dim salmons As New List(Of String) From
{"chinook", "coho", "pink", "sockeye"}
For Each salmon As String In salmons
Console.Write(salmon & " ")
Next
'Output: chinook coho pink sockeye
// 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…Next (Visual Basic) 或 for (C#) 语句(而非 For Each 语句)来循环访问集合。 按索引位置访问集合元素以完成此操作。 元素的索引从 0 开始,在元素计数减 1 处结束。
下面的示例通过使用 For…Next 而不是 For Each 重复访问集合的元素。
Dim salmons As New List(Of String) From
{"chinook", "coho", "pink", "sockeye"}
For index = 0 To salmons.Count - 1
Console.Write(salmons(index) & " ")
Next
'Output: chinook coho pink sockeye
// 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
下面的示例通过指定删除对象移除集合中的元素。
' Create a list of strings by using a
' collection initializer.
Dim salmons As New List(Of String) From
{"chinook", "coho", "pink", "sockeye"}
' Remove an element in the list by specifying
' the object.
salmons.Remove("coho")
For Each salmon As String In salmons
Console.Write(salmon & " ")
Next
'Output: chinook pink sockeye
// Create a list of strings by using a
// collection initializer.
var salmons = new List<string> { "chinook", "coho", "pink", "sockeye" };
// Remove an element from the list by specifying
// the object.
salmons.Remove("coho");
// Iterate through the list.
foreach (var salmon in salmons)
{
Console.Write(salmon + " ");
}
// Output: chinook pink sockeye
下面的示例从泛型列表中删除元素。 使用采用降序迭代的 For…Next (Visual Basic) 或 for (C#) 语句,而非 For Each 语句。 这是因为 RemoveAt 方法会导致删除某个元素之后的元素具有较小的索引值。
Dim numbers As New List(Of Integer) From
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
' Remove odd numbers.
For index As Integer = numbers.Count - 1 To 0 Step -1
If numbers(index) Mod 2 = 1 Then
' Remove the element by specifying
' the zero-based index in the list.
numbers.RemoveAt(index)
End If
Next
' Iterate through the list.
' A lambda expression is placed in the ForEach method
' of the List(T) object.
numbers.ForEach(
Sub(number) Console.Write(number & " "))
' Output: 0 2 4 6 8
var numbers = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// Remove odd numbers.
for (var index = numbers.Count - 1; index >= 0; index--)
{
if (numbers[index] % 2 == 1)
{
// Remove the element by specifying
// the zero-based index in the list.
numbers.RemoveAt(index);
}
}
// Iterate through the list.
// A lambda expression is placed in the ForEach method
// of the List(T) object.
numbers.ForEach(
number => Console.Write(number + " "));
// Output: 0 2 4 6 8
对于 List 中的元素类型,您还可以定义自己的类。 在下面的示例中,List 使用的 Galaxy 类在代码中定义。
Private Sub IterateThroughList()
Dim theGalaxies As New List(Of Galaxy) From
{
New Galaxy With {.Name = "Tadpole", .MegaLightYears = 400},
New Galaxy With {.Name = "Pinwheel", .MegaLightYears = 25},
New Galaxy With {.Name = "Milky Way", .MegaLightYears = 0},
New Galaxy With {.Name = "Andromeda", .MegaLightYears = 3}
}
For Each theGalaxy In theGalaxies
With theGalaxy
Console.WriteLine(.Name & " " & .MegaLightYears)
End With
Next
' Output:
' Tadpole 400
' Pinwheel 25
' Milky Way 0
' Andromeda 3
End Sub
Public Class Galaxy
Public Property Name As String
Public Property MegaLightYears As Integer
End Class
private 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; }
}
集合的类型
许多常见的集合是由 .NET Framework 提供的。 每一类型的集合都是为特定用途设计的。
本节将对以下集合选件类组进行描述:
System.Collections.Generic 类
System.Collections.Concurrent 类
System.Collections 类
Visual Basic Collection 类
System.Collections.Generic 类
可以通过使用 System.Collections.Generic 命名空间中的一类来创建泛型集合。 当泛型集合中的所有项具有相同的数据类型时,泛型集合很有用。 泛型集合通过仅允许添加所需的数据类型来强制实施“强类型”。
下表列出了一些 System.Collections.Generic 命名空间中常用的选件类:
类 |
描述 |
表示根据键进行组织的键/值对的集合。 |
|
表示可通过索引访问的对象的列表。 提供用于对列表进行搜索、排序和修改的方法。 |
|
表示对象的先进先出 (FIFO) 集合。 |
|
表示根据键进行排序的键/值对的集合,而键基于的是相关的 IComparer 实现。 |
|
表示对象的后进先出 (LIFO) 集合。 |
有关附加信息,请参见 常用的集合类型、选择集合类 和 System.Collections.Generic。
System.Collections.Concurrent 类
在 .NET Framework 4 中,System.Collections.Concurrent 命名空间中的集合可提供有效的线程安全操作,以便从多个线程访问集合项。
当有多个线程并发访问集合时,应使用 System.Collections.Concurrent 命名空间中的类代替 System.Collections.Generic 和 System.Collections 命名空间中的对应类型。 有关更多信息,请参见线程安全集合和System.Collections.Concurrent。
包含在 System.Collections.Concurrent 命名空间中的部分类是 BlockingCollection、ConcurrentDictionary、ConcurrentQueue 和 ConcurrentStack。
System.Collections 类
System.Collections 命名空间中的类不会将元素存储为指定类型的对象,而是存储为 Object 类型的对象。
只要有可能,就应使用 System.Collections.Generic 或 System.Collections.Concurrent 命名空间中的泛型集合来替代 System.Collections 命名空间中的旧类型。
下表列出了一些 System.Collections 命名空间中常用的选件类:
类 |
描述 |
表示大小根据需要动态增加的对象数组。 |
|
表示根据键的哈希代码进行组织的键/值对的集合。 |
|
表示对象的先进先出 (FIFO) 集合。 |
|
表示对象的后进先出 (LIFO) 集合。 |
System.Collections.Specialized 命名空间提供了专用集合类和强类型的集合类,如只包含字符串的集合以及链接列表和混合字典。
Visual Basic 集合类
通过使用数值索引或 String 关键值,可以使用 Visual Basic Collection 类访问集合项。 可以在指定或不指定键的情况下将项添加到集合对象。 如果添加一个没有键的项,则必须使用其数值索引才能访问它。
Visual Basic Collection 类将其所有元素存储为 Object 类型,以便您可以添加任何数据类型的项。 没有保护措施来防止添加不适当的数据类型。
当您使用 Visual Basic Collection 类时,集合中第一项的索引为 1。 这与 .NET Framework 集合选件类不同,因为 .NET Framework 集合选件类的起始索引为 0。
只要有可能,就应使用 System.Collections.Generic 命名空间或 System.Collections.Concurrent 命名空间中的泛型集合,而不是使用 Visual Basic Collection 类。
有关更多信息,请参见 Collection。
实现键/值对集合
Dictionary 泛型集合使您能够通过使用每个元素的键来访问集合中的元素。 字典中的每个添加项都由一个值及其相关联的键组成。 通过值的键来检索值速度快,这是因为 Dictionary 类作为一个哈希表实现。
下面的示例创建了 Dictionary 集合,并通过使用 For Each 语句,重复访问字典。
Private Sub IterateThroughDictionary()
Dim elements As Dictionary(Of String, Element) = BuildDictionary()
For Each kvp As KeyValuePair(Of String, Element) In elements
Dim theElement As Element = kvp.Value
Console.WriteLine("key: " & kvp.Key)
With theElement
Console.WriteLine("values: " & .Symbol & " " &
.Name & " " & .AtomicNumber)
End With
Next
End Sub
Private Function BuildDictionary() As Dictionary(Of String, Element)
Dim elements As New Dictionary(Of String, Element)
AddToDictionary(elements, "K", "Potassium", 19)
AddToDictionary(elements, "Ca", "Calcium", 20)
AddToDictionary(elements, "Sc", "Scandium", 21)
AddToDictionary(elements, "Ti", "Titanium", 22)
Return elements
End Function
Private Sub AddToDictionary(ByVal elements As Dictionary(Of String, Element),
ByVal symbol As String, ByVal name As String, ByVal atomicNumber As Integer)
Dim theElement As New Element
theElement.Symbol = symbol
theElement.Name = name
theElement.AtomicNumber = atomicNumber
elements.Add(Key:=theElement.Symbol, value:=theElement)
End Sub
Public Class Element
Public Property Symbol As String
Public Property Name As String
Public Property AtomicNumber As Integer
End Class
private void IterateThruDictionary()
{
Dictionary<string, Element> elements = BuildDictionary();
foreach (KeyValuePair<string, Element> kvp in elements)
{
Element theElement = kvp.Value;
Console.WriteLine("key: " + kvp.Key);
Console.WriteLine("values: " + theElement.Symbol + " " +
theElement.Name + " " + theElement.AtomicNumber);
}
}
private Dictionary<string, Element> BuildDictionary()
{
var elements = new Dictionary<string, Element>();
AddToDictionary(elements, "K", "Potassium", 19);
AddToDictionary(elements, "Ca", "Calcium", 20);
AddToDictionary(elements, "Sc", "Scandium", 21);
AddToDictionary(elements, "Ti", "Titanium", 22);
return elements;
}
private void AddToDictionary(Dictionary<string, Element> elements,
string symbol, string name, int atomicNumber)
{
Element theElement = new Element();
theElement.Symbol = symbol;
theElement.Name = name;
theElement.AtomicNumber = atomicNumber;
elements.Add(key: theElement.Symbol, value: theElement);
}
public class Element
{
public string Symbol { get; set; }
public string Name { get; set; }
public int AtomicNumber { get; set; }
}
若要改用集合初始值设定项生成 Dictionary 集合,您可以使用下面的方法替换 BuildDictionary 和 AddToDictionary 方法。
Private Function BuildDictionary2() As Dictionary(Of String, Element)
Return New Dictionary(Of String, Element) From
{
{"K", New Element With
{.Symbol = "K", .Name = "Potassium", .AtomicNumber = 19}},
{"Ca", New Element With
{.Symbol = "Ca", .Name = "Calcium", .AtomicNumber = 20}},
{"Sc", New Element With
{.Symbol = "Sc", .Name = "Scandium", .AtomicNumber = 21}},
{"Ti", New Element With
{.Symbol = "Ti", .Name = "Titanium", .AtomicNumber = 22}}
}
End Function
private Dictionary<string, Element> BuildDictionary2()
{
return new Dictionary<string, Element>
{
{"K",
new Element() { Symbol="K", Name="Potassium", AtomicNumber=19}},
{"Ca",
new Element() { Symbol="Ca", Name="Calcium", AtomicNumber=20}},
{"Sc",
new Element() { Symbol="Sc", Name="Scandium", AtomicNumber=21}},
{"Ti",
new Element() { Symbol="Ti", Name="Titanium", AtomicNumber=22}}
};
}
下面的示例使用 ContainsKey 方法和 Dictionary 的 Item 属性,以通过键快速查找到项。 Item 属性可使您通过使用 Visual Basic 中的 elements(symbol) 代码或 C# 中的 elements[symbol] 代码,访问 elements 集合中的一个项。
Private Sub FindInDictionary(ByVal symbol As String)
Dim elements As Dictionary(Of String, Element) = BuildDictionary()
If elements.ContainsKey(symbol) = False Then
Console.WriteLine(symbol & " not found")
Else
Dim theElement = elements(symbol)
Console.WriteLine("found: " & theElement.Name)
End If
End Sub
private void FindInDictionary(string symbol)
{
Dictionary<string, Element> elements = BuildDictionary();
if (elements.ContainsKey(symbol) == false)
{
Console.WriteLine(symbol + " not found");
}
else
{
Element theElement = elements[symbol];
Console.WriteLine("found: " + theElement.Name);
}
}
相反,下面的示例使用 TryGetValue 方法通过键快速查找项。
Private Sub FindInDictionary2(ByVal symbol As String)
Dim elements As Dictionary(Of String, Element) = BuildDictionary()
Dim theElement As Element = Nothing
If elements.TryGetValue(symbol, theElement) = False Then
Console.WriteLine(symbol & " not found")
Else
Console.WriteLine("found: " & theElement.Name)
End If
End Sub
private void FindInDictionary2(string symbol)
{
Dictionary<string, Element> elements = BuildDictionary();
Element theElement = null;
if (elements.TryGetValue(symbol, out theElement) == false)
Console.WriteLine(symbol + " not found");
else
Console.WriteLine("found: " + theElement.Name);
}
使用 LINQ 访问集合
LINQ(语言集成查询)可用于访问集合。 LINQ 查询提供筛选、排序和分组功能。 有关更多信息,请参见Visual Basic 中的 LINQ 入门或C# 中的 LINQ 入门。
下面的示例对泛型 List 执行 LINQ 查询。 LINQ 查询返回包含结果的不同集合。
Private Sub ShowLINQ()
Dim elements As List(Of Element) = BuildList()
' LINQ Query.
Dim subset = From theElement In elements
Where theElement.AtomicNumber < 22
Order By theElement.Name
For Each theElement In subset
Console.WriteLine(theElement.Name & " " & theElement.AtomicNumber)
Next
' Output:
' Calcium 20
' Potassium 19
' Scandium 21
End Sub
Private Function BuildList() As List(Of Element)
Return New List(Of Element) From
{
{New Element With
{.Symbol = "K", .Name = "Potassium", .AtomicNumber = 19}},
{New Element With
{.Symbol = "Ca", .Name = "Calcium", .AtomicNumber = 20}},
{New Element With
{.Symbol = "Sc", .Name = "Scandium", .AtomicNumber = 21}},
{New Element With
{.Symbol = "Ti", .Name = "Titanium", .AtomicNumber = 22}}
}
End Function
Public Class Element
Public Property Symbol As String
Public Property Name As String
Public Property AtomicNumber As Integer
End Class
private void ShowLINQ()
{
List<Element> elements = BuildList();
// LINQ Query.
var subset = from theElement in elements
where theElement.AtomicNumber < 22
orderby theElement.Name
select theElement;
foreach (Element theElement in subset)
{
Console.WriteLine(theElement.Name + " " + theElement.AtomicNumber);
}
// Output:
// Calcium 20
// Potassium 19
// Scandium 21
}
private List<Element> BuildList()
{
return new List<Element>
{
{ new Element() { Symbol="K", Name="Potassium", AtomicNumber=19}},
{ new Element() { Symbol="Ca", Name="Calcium", AtomicNumber=20}},
{ new Element() { Symbol="Sc", Name="Scandium", AtomicNumber=21}},
{ new Element() { Symbol="Ti", Name="Titanium", AtomicNumber=22}}
};
}
public class Element
{
public string Symbol { get; set; }
public string Name { get; set; }
public int AtomicNumber { get; set; }
}
排序集合
下面的示例演示了排序集合的方法。 该示例对存储在 List中的 Car 选件类实例进行排序。 Car 选件类实现了 IComparable 接口,需执行 CompareTo 方法。
每次对 CompareTo 方法的调用都会产生用于排序的单个比较。 每次比较当前对象和其他对象时,CompareTo 方法中用户编写的代码都会返回一个值。 如果当前对象小于第二个对象,则该方法返回小于零的值,如果当前对象大于第二个对象,则返回大于零的值,如果两个对象相等,则返回零。 这使您可以用代码定义大于、小于和等于的标准。
在 ListCars 方法中,cars.Sort() 语句对列表进行排序。 该项对 List 中 Sort 方法的调用,会导致对 List 中 Car 对象的CompareTo 方法的自动调动。
Public Sub ListCars()
' Create some new cars.
Dim cars As New List(Of Car) From
{
New Car With {.Name = "car1", .Color = "blue", .Speed = 20},
New Car With {.Name = "car2", .Color = "red", .Speed = 50},
New Car With {.Name = "car3", .Color = "green", .Speed = 10},
New Car With {.Name = "car4", .Color = "blue", .Speed = 50},
New Car With {.Name = "car5", .Color = "blue", .Speed = 30},
New Car With {.Name = "car6", .Color = "red", .Speed = 60},
New Car With {.Name = "car7", .Color = "green", .Speed = 50}
}
' Sort the cars by color alphabetically, and then by speed
' in descending order.
cars.Sort()
' View all of the cars.
For Each thisCar As Car In cars
Console.Write(thisCar.Color.PadRight(5) & " ")
Console.Write(thisCar.Speed.ToString & " ")
Console.Write(thisCar.Name)
Console.WriteLine()
Next
' Output:
' blue 50 car4
' blue 30 car5
' blue 20 car1
' green 50 car7
' green 10 car3
' red 60 car6
' red 50 car2
End Sub
Public Class Car
Implements IComparable(Of Car)
Public Property Name As String
Public Property Speed As Integer
Public Property Color As String
Public Function CompareTo(ByVal other As Car) As Integer _
Implements System.IComparable(Of Car).CompareTo
' A call to this method makes a single comparison that is
' used for sorting.
' Determine the relative order of the objects being compared.
' Sort by color alphabetically, and then by speed in
' descending order.
' Compare the colors.
Dim compare As Integer
compare = String.Compare(Me.Color, other.Color, True)
' If the colors are the same, compare the speeds.
If compare = 0 Then
compare = Me.Speed.CompareTo(other.Speed)
' Use descending order for speed.
compare = -compare
End If
Return compare
End Function
End Class
private void ListCars()
{
var cars = new List<Car>
{
{ new Car() { Name = "car1", Color = "blue", Speed = 20}},
{ new Car() { Name = "car2", Color = "red", Speed = 50}},
{ new Car() { Name = "car3", Color = "green", Speed = 10}},
{ new Car() { Name = "car4", Color = "blue", Speed = 50}},
{ new Car() { Name = "car5", Color = "blue", Speed = 30}},
{ new Car() { Name = "car6", Color = "red", Speed = 60}},
{ new Car() { Name = "car7", Color = "green", Speed = 50}}
};
// Sort the cars by color alphabetically, and then by speed
// in descending order.
cars.Sort();
// View all of the cars.
foreach (Car thisCar in cars)
{
Console.Write(thisCar.Color.PadRight(5) + " ");
Console.Write(thisCar.Speed.ToString() + " ");
Console.Write(thisCar.Name);
Console.WriteLine();
}
// Output:
// blue 50 car4
// blue 30 car5
// blue 20 car1
// green 50 car7
// green 10 car3
// red 60 car6
// red 50 car2
}
public class Car : IComparable<Car>
{
public string Name { get; set; }
public int Speed { get; set; }
public string Color { get; set; }
public int CompareTo(Car other)
{
// A call to this method makes a single comparison that is
// used for sorting.
// Determine the relative order of the objects being compared.
// Sort by color alphabetically, and then by speed in
// descending order.
// Compare the colors.
int compare;
compare = String.Compare(this.Color, other.Color, true);
// If the colors are the same, compare the speeds.
if (compare == 0)
{
compare = this.Speed.CompareTo(other.Speed);
// Use descending order for speed.
compare = -compare;
}
return compare;
}
}
定义自定义集合
可以通过实现 IEnumerable 或 IEnumerable 接口定义集合。 有关其他信息,请参见 枚举集合 和 如何:使用 foreach 访问集合类(C# 编程指南)。
虽然您可以定义自定义集合,但通常最好使用包括在 .NET Framework(本主题前面的集合类型中有所介绍)中的集合。
下面的示例定义名为 AllColors 的客户集合类。 该选件类实现了 IEnumerable 接口,需执行 GetEnumerator 方法。
GetEnumerator 方法返回 ColorEnumerator 类的一个实例。 ColorEnumerator 实现 IEnumerator 接口,这需要首先实现 Current 属性、MoveNext 方法和 Reset 方法。
Public Sub ListColors()
Dim colors As New AllColors()
For Each theColor As Color In colors
Console.Write(theColor.Name & " ")
Next
Console.WriteLine()
' Output: red blue green
End Sub
' Collection class.
Public Class AllColors
Implements System.Collections.IEnumerable
Private _colors() As Color =
{
New Color With {.Name = "red"},
New Color With {.Name = "blue"},
New Color With {.Name = "green"}
}
Public Function GetEnumerator() As System.Collections.IEnumerator _
Implements System.Collections.IEnumerable.GetEnumerator
Return New ColorEnumerator(_colors)
' Instead of creating a custom enumerator, you could
' use the GetEnumerator of the array.
'Return _colors.GetEnumerator
End Function
' Custom enumerator.
Private Class ColorEnumerator
Implements System.Collections.IEnumerator
Private _colors() As Color
Private _position As Integer = -1
Public Sub New(ByVal colors() As Color)
_colors = colors
End Sub
Public ReadOnly Property Current() As Object _
Implements System.Collections.IEnumerator.Current
Get
Return _colors(_position)
End Get
End Property
Public Function MoveNext() As Boolean _
Implements System.Collections.IEnumerator.MoveNext
_position += 1
Return (_position < _colors.Length)
End Function
Public Sub Reset() Implements System.Collections.IEnumerator.Reset
_position = -1
End Sub
End Class
End Class
' Element class.
Public Class Color
Public Property Name As String
End Class
private void ListColors()
{
var colors = new AllColors();
foreach (Color theColor in colors)
{
Console.Write(theColor.Name + " ");
}
Console.WriteLine();
// Output: red blue green
}
// Collection class.
public class AllColors : System.Collections.IEnumerable
{
Color[] _colors =
{
new Color() { Name = "red" },
new Color() { Name = "blue" },
new Color() { Name = "green" }
};
public System.Collections.IEnumerator GetEnumerator()
{
return new ColorEnumerator(_colors);
// Instead of creating a custom enumerator, you could
// use the GetEnumerator of the array.
//return _colors.GetEnumerator();
}
// Custom enumerator.
private class ColorEnumerator : System.Collections.IEnumerator
{
private Color[] _colors;
private int _position = -1;
public ColorEnumerator(Color[] colors)
{
_colors = colors;
}
object System.Collections.IEnumerator.Current
{
get
{
return _colors[_position];
}
}
bool System.Collections.IEnumerator.MoveNext()
{
_position++;
return (_position < _colors.Length);
}
void System.Collections.IEnumerator.Reset()
{
_position = -1;
}
}
}
// Element class.
public class Color
{
public string Name { get; set; }
}
迭代器
“迭代器”用于对集合执行自定义迭代。 迭代器可以是一种方法或一个 get 访问器。 迭代器使用一个 yield (Visual Basic) 或 return (c#) 语句一次性返回集合中的每个元素。
使用 For Each…Next (Visual Basic) 或 foreach (C#) 语句调用迭代器。 For Each 循环的每次迭代都会调用迭代器。 迭代器运行到 Yield 或 yield return 语句时,会返回一个表达式并保留当前在代码中的位置。 下次调用迭代器时将从此位置重新开始执行。
有关详细信息,请参阅 迭代器(C# 和 Visual Basic)。
下面的示例使用了迭代器方法。 迭代器方法具有在 For…Next (Visual Basic) 中或 用于 (C#) 循环的 Yield 或 yield return 语句。 在 ListEvenNumbers 方法中,For Each 语句体的每个迭代创建对迭代器方法的调用,该调用继续到下一个 Yield 或 yield return 语句。
Public Sub ListEvenNumbers()
For Each number As Integer In EvenSequence(5, 18)
Console.Write(number & " ")
Next
Console.WriteLine()
' Output: 6 8 10 12 14 16 18
End Sub
Private Iterator Function EvenSequence(
ByVal firstNumber As Integer, ByVal lastNumber As Integer) _
As IEnumerable(Of Integer)
' Yield even numbers in the range.
For number = firstNumber To lastNumber
If number Mod 2 = 0 Then
Yield number
End If
Next
End Function
private void ListEvenNumbers()
{
foreach (int number in EvenSequence(5, 18))
{
Console.Write(number.ToString() + " ");
}
Console.WriteLine();
// Output: 6 8 10 12 14 16 18
}
private static IEnumerable<int> EvenSequence(
int firstNumber, int lastNumber)
{
// Yield even numbers in the range.
for (var number = firstNumber; number <= lastNumber; number++)
{
if (number % 2 == 0)
{
yield return number;
}
}
}