在 C# 中,集合是提供了一种方便处理一组对象的类。
例如,
System.Collections.Generic
类提供了强类型实体(如列表、栈等)的实现。
C# 集合类的类型
在 C# 中,集合分为 **3** 类。它们是
- System.Collections.Generic
- System.Collections
- System.Collections.Concurrent
让我们更详细地了解每个类!
System.Collections.Generic 类
System.Collections.Generic
类帮助我们创建泛型集合。在其中,我们存储类型兼容的数据元素。此集合不允许我们存储不同类型的数据元素。
让我们以泛型类 `List<T>` 为例。
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
// create a list named number that contains integer data items
List<int> number = new List<int>();
number.Add(1);
number.Add(2);
number.Add("Programiz");
Console.WriteLine(number[1]); //
}
}
上面的代码会抛出以下错误
Argument 1: cannot convert from 'string' to 'int'
在这里,我们已经定义了 `number` 列表的类型为 `int`。
由于 `List<T>` 属于泛型集合,我们不能添加不同数据类型的元素(即 `string`)。
一些 System.Collections.Generic 类
在 C# 中,以下类属于 `System.Collections.Generic` 命名空间
1. List类
List<T>
类用于存储 **相同数据类型** 的多个元素,这些元素可以通过索引访问。我们可以向列表中添加、插入和删除元素。此外,我们可以动态更改列表的大小。
2. Stack类
Stack<T>
类也是泛型的,这意味着我们存储相同数据类型的元素。
在栈中,元素以 LIFO(后进先出)的方式存储。借助方法,我们可以对栈执行操作
Push()
- 插入元素Pop()
- 删除元素
3. Queue类
在 `Queue<T>` 类中,对象以 FIFO(先进先出)的方式存储。在这里,元素在一个末端插入,在另一个末端移除。它使用循环队列实现。我们可以使用诸如下面的方法执行操作
Enqueue()
- 添加元素Dequeue()
- 删除元素
4. SortedList类
SortedList<TKey,TValue>
是一个数组,包含按顺序排序的键/值对。SortedList<TKey,TValue>
中的每个键都必须是唯一的,并且使用这些键我们可以访问其中的元素。键不允许为 `null`。
System.Collections 类
在 C# 中,System.Collections
类帮助我们创建 **非泛型** 集合。
为此,我们使用 System.Collections
命名空间。使用它,我们可以创建可以添加多种数据类型元素的类。
以下是 System.Collections
命名空间中的一些类
1. ArrayList 类
ArrayList
是非泛型的,这意味着我们可以存储多种数据类型的元素。我们使用 ArrayList
类来实现可调整大小数组的功能。ArrayList
中允许重复元素。
我们可以使用 sort 方法对其中的元素进行排序。
2. Hashtable 类
Hashtable
也是非泛型的,它包含由特定键的哈希码管理的键/值对。键不能为 `null`,但值可以为 null。我们可以在 Hashtable
中执行动态内存分配。
System.Collections.Concurrent 类
System.Collections.Concurrent
提供了一些集合类,有助于实现线程安全的代码。
什么是线程安全?
当多个线程尝试执行同一段代码时,可能会出现这种情况。如果代码无论多少线程并发访问都能正确执行,则该代码被认为是“线程安全”的。
当多个线程访问集合时,建议使用 System.Collections.Concurrent
类,而不是 System.Collections
和 System.Collections.Generic
类。
一些线程安全的集合类是
ConcurrentStack<T>
ConcurrentQueue<T>
ConcurrentDictionary<TKey,TValue>