泛型(Generic)※
泛型允许在定义类/方法时不指定具体类型,在使用时再传入,实现类型安全的代码复用(编译时检查,避免装箱拆箱)。
泛型类※
public class Box { private T _value; public Box(T value) { _value = value; } public T GetValue() => _value; } var intBox = new Box(123); var strBox = new Box("hello");泛型方法※
public T Max(T a, T b) where T : IComparable { return a.CompareTo(b) > 0 ? a : b; }泛型约束(where)※
where T : class // 引用类型
where T : struct // 值类型
where T : IComparable // 实现接口
where T : new() // 有无参构造函数
where T : BaseClass // 继承自基类
常用泛型集合※
List<T>、Dictionary<K,V>、Queue<T>、Stack<T>、HashSet<T>
泛型优点※
- 类型安全(编译期检查)
- 性能(值类型免装箱)
- 代码复用