System.Collections.Generic

System.Collections.Generic 是.NET框架中的一个命名空间,它提供了一系列泛型集合类和接口,用于存储和操作一组对象。与非泛型集合(如 System.Collections 命名空间中的集合)相比,泛型集合提供了类型安全、性能优化和更好的代码可读性。

主要功能

1. 类型安全

泛型集合在编译时检查类型,避免了类型转换错误和运行时异常。

2. 性能优化

泛型集合避免了装箱和拆箱操作,提高了性能,尤其是处理值类型(如 intdouble 等)时。

3. 代码可读性

泛型集合通过明确指定类型,使代码更加清晰和易于维护。

常用类和接口

1. List<T>

List<T> 是一个动态数组,提供了对元素的快速访问和动态扩展功能。
  • 创建和使用 List<T>
    csharp
    复制
    using 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>
    csharp
    复制
    using 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>
    csharp
    复制
    using 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>
    csharp
    复制
    using 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>
    csharp
    复制
    using 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(stack.Pop());
        }

        // 使用 HashSet<T>
        HashSet<int> uniqueNumbers = new HashSet<int> { 1, 2, 3, 4, 5 };
        uniqueNumbers.Add(6);
        uniqueNumbers.Remove(3);

        Console.WriteLine("\nHashSet:");
        foreach (int number in uniqueNumbers)
        {
            Console.WriteLine(number);
        }
    }
}
 

注意事项

  1. 性能优化
    • 选择合适的集合类型可以显著提高性能。例如,HashSet<T> 提供了最快的查找性能,但不保证元素的顺序。
  2. 线程安全
    • 大多数泛型集合不是线程安全的。如果需要在多线程环境中使用,可以使用 ConcurrentCollections 命名空间中的线程安全集合。
  3. 内存管理
    • 注意集合的容量和大小,避免不必要的内存分配。例如,List<T>Capacity 属性可以优化内存使用。
  4. 异常处理
    • 在操作集合时,可能会遇到异常,如 KeyNotFoundExceptionInvalidOperationException 等。确保正确处理这些异常,避免程序崩溃。

总结

System.Collections.Generic 提供了一套强大的泛型集合类和接口,用于存储和操作一组对象。通过使用 List<T>Dictionary<TKey, TValue>Queue<T>Stack<T>HashSet<T> 等类,开发者可以实现类型安全、性能优化和代码可读性的目标。合理选择和使用这些集合可以提高应用程序的性能和可靠性,同时确保代码的简洁性和可维护性。
posted @ 2025-05-15 15:21  yinghualeihenmei  阅读(89)  评论(0)    收藏  举报