什么是泛型?
泛型(Generics) 是一种编程技能,广泛应用于面向对象编程(OOP)中,特殊是在C#、Java等现代编程语言中。泛型的核心思想是创建可以在多种数据范例上工作的类、接口和方法,而不需要为每种数据范例单独编写代码。这不但进步了代码的重用性,还增强了范例安全性,减少了运行时错误。
泛型的主要优点
- 范例安全性:
- 泛型在编译时举行范例检查,确保范例的一致性,减少运行时范例转换错误。
- 代码重用:
- 通过泛型,可以编写适用于多种数据范例的通用代码,而不需要为每种数据范例编写单独的实现。
- 性能提升:
- 泛型避免了装箱(boxing)和拆箱(unboxing)操作,进步了性能,特殊是在处理值范例时。
- 可读性和可维护性:
- 泛型代码更易于阅读和维护,因为范例信息在编译时就已经明确。
泛型的实现
<ol>泛型类:
定义一个类,使其可以处理多种数据范例的实例。- public class Box<T>
- {
- private T _content;
- public void SetContent(T content)
- {
- _content = content;
- }
- public T GetContent()
- {
- return _content;
- }
- }
- public class Program
- {
- public static void Main()
- {
- Box<int> intBox = new Box<int>();
- intBox.SetContent(42);
- Console.WriteLine(intBox.GetContent()); // 输出: 42
- Box<string> stringBox = new Box<string>();
- stringBox.SetContent("Hello, World!");
- Console.WriteLine(stringBox.GetContent()); // 输出: Hello, World!
- }
- }
复制代码 泛型接口:
定义一个接口,使其可以处理多种数据范例的实例。- public interface IStorage<T>
- {
- void Store(T item);
- T Retrieve();
- }
- public class Storage<T> : IStorage<T>
- {
- private T _item;
- public void Store(T item)
- {
- _item = item;
- }
- public T Retrieve()
- {
- return _item;
- }
- }
- public class Program
- {
- public static void Main()
- {
- IStorage<int> intStorage = new Storage<int>();
- intStorage.Store(100);
- Console.WriteLine(intStorage.Retrieve()); // 输出: 100
- IStorage<string> stringStorage = new Storage<string>();
- stringStorage.Store("Generic Storage");
- Console.WriteLine(stringStorage.Retrieve()); // 输出: Generic Storage
- }
- }
复制代码 泛型方法:
定义一个方法,使其可以处理多种数据范例的参数和返回值。- public class GenericMethods
- {
- public static T GetDefault<T>() where T : new()
- {
- return new T();
- }
- public static void Print<T>(T item)
- {
- Console.WriteLine(item);
- }
- }
- public class Program
- {
- public static void Main()
- {
- int defaultInt = GenericMethods.GetDefault<int>();
- Console.WriteLine(defaultInt); // 输出: 0
- string defaultString = GenericMethods.GetDefault<string>();
- Console.WriteLine(defaultString); // 输出: (空字符串)
- GenericMethods.Print(42); // 输出: 42
- GenericMethods.Print("Hello, World!"); // 输出: Hello, World!
- }
- }
复制代码 泛型约束:
可以为泛型类、接口和方法添加约束,以限制泛型参数的范例。
常见的约束包括:
- where T : new():要求泛型参数必须有一个无参构造函数。
- where T : class:要求泛型参数必须是引用范例。
- where T : struct:要求泛型参数必须是值范例。
- where T : IInterface:要求泛型参数必须实现特定的接口。
- where T : BaseClass:要求泛型参数必须继续自特定的基类。
- public class GenericConstraint<T> where T : new()
- {
- public T CreateInstance()
- {
- return new T();
- }
- }
- public class MyClass
- {
- public void MyMethod()
- {
- Console.WriteLine("MyClass instance created.");
- }
- }
- public class Program
- {
- public static void Main()
- {
- GenericConstraint<MyClass> constraint = new GenericConstraint<MyClass>();
- MyClass instance = constraint.CreateInstance();
- instance.MyMethod(); // 输出: MyClass instance created.
- }
- }
复制代码
泛型的应用场景
1.集合类:
泛型集合类(如List |