System.Collections.Generic
System.Collections.Generic 是.NET框架中的一个命名空间,它提供了一系列泛型集合类和接口,用于存储和操作一组对象。与非泛型集合(如 System.Collections 命名空间中的集合)相比,泛型集合提供了类型安全、性能优化和更好的代码可读性。主要功能
1. 类型安全
泛型集合在编译时检查类型,避免了类型转换错误和运行时异常。
2. 性能优化
泛型集合避免了装箱和拆箱操作,提高了性能,尤其是处理值类型(如
int、double 等)时。3. 代码可读性
泛型集合通过明确指定类型,使代码更加清晰和易于维护。
常用类和接口
1. List<T>
List<T> 是一个动态数组,提供了对元素的快速访问和动态扩展功能。-
创建和使用
List<T>csharpusing System; using System.Collections.Generic; class Program { static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; numbers.Add(6); numbers.RemoveAt(0); foreach (int number in numbers) { Console.WriteLine(number); } } }
2. Dictionary<TKey, TValue>
Dictionary<TKey, TValue> 是一个键值对集合,提供了快速的查找功能。-
创建和使用
Dictionary<TKey, TValue>csharpusing System; using System.Collections.Generic; class Program { static void Main() { Dictionary<string, int> ages = new Dictionary<string, int> { { "Alice", 30 }, { "Bob", 25 } }; ages["Charlie"] = 35; foreach (var pair in ages) { Console.WriteLine($"{pair.Key}: {pair.Value}"); } } }
3. Queue<T>
Queue<T> 是一个先进先出(FIFO)的集合,提供了入队和出队操作。-
创建和使用
Queue<T>csharpusing System; using System.Collections.Generic; class Program { static void Main() { Queue<string> queue = new Queue<string>(); queue.Enqueue("First"); queue.Enqueue("Second"); queue.Enqueue("Third"); while (queue.Count > 0) { Console.WriteLine(queue.Dequeue()); } } }
4. Stack<T>
Stack<T> 是一个后进先出(LIFO)的集合,提供了入栈和出栈操作。-
创建和使用
Stack<T>csharpusing System; using System.Collections.Generic; class Program { static void Main() { Stack<string> stack = new Stack<string>(); stack.Push("First"); stack.Push("Second"); stack.Push("Third"); while (stack.Count > 0) { Console.WriteLine(stack.Pop()); } } }
5. HashSet<T>
HashSet<T> 是一个无序的集合,提供了快速的查找功能,且不允许重复元素。-
创建和使用
HashSet<T>csharpusing System; using System.Collections.Generic; class Program { static void Main() { HashSet<int> numbers = new HashSet<int> { 1, 2, 3, 4, 5 }; numbers.Add(6); numbers.Remove(3); foreach (int number in numbers) { Console.WriteLine(number); } } }
示例代码
完整示例:使用多种泛型集合
csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 使用 List<T>
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
numbers.Add(6);
numbers.RemoveAt(0);
Console.WriteLine("List:");
foreach (int number in numbers)
{
Console.WriteLine(number);
}
// 使用 Dictionary<TKey, TValue>
Dictionary<string, int> ages = new Dictionary<string, int>
{
{ "Alice", 30 },
{ "Bob", 25 }
};
ages["Charlie"] = 35;
Console.WriteLine("\nDictionary:");
foreach (var pair in ages)
{
Console.WriteLine($"{pair.Key}: {pair.Value}");
}
// 使用 Queue<T>
Queue<string> queue = new Queue<string>();
queue.Enqueue("First");
queue.Enqueue("Second");
queue.Enqueue("Third");
Console.WriteLine("\nQueue:");
while (queue.Count > 0)
{
Console.WriteLine(queue.Dequeue());
}
// 使用 Stack<T>
Stack<string> stack = new Stack<string>();
stack.Push("First");
stack.Push("Second");
stack.Push("Third");
Console.WriteLine("\nStack:");
while (stack.Count > 0)
{
Console.WriteLine