泛型是C#核心特性,通过类型参数实现类型安全、高效和可重用的代码;支持泛型类、方法、委托及约束,编译时生成独立IL,避免运行时错误和装箱拆箱。

泛型是 C# 的核心特性之一,它让代码更安全、更高效、也更可重用。不用写一堆相似的类或方法来处理 int、string、Customer 等不同类型,一个泛型就能通吃。
泛型类:定义一次,适配多种类型
泛型类用
public class Stack
{
private List
public void Push(T item) => _items.Add(item);
public T Pop()
{
if (_items.Count == 0) throw new InvalidOperationException();
var last = _items[^1];
_items.RemoveAt(_items.Count - 1);
return last;
}
}
使用时指定实际类型:
var intStack = new Stack
intStack.Push(42);
int x = intStack.Pop();
var strStack = new Stack
strStack.Push("hello");
注意点:
• 类型参数名常用 T(Type),多个可用 TKey、TValue 等
• 可加约束(如 where T : class 或 where T : IComparable)来限定能传入的类型
• 编译后每个封闭泛型类型(如 Stack
泛型方法:局部泛化,按需推断
方法也能泛型化,尤其适合工具函数。类型参数写在方法名后:
public static T GetDefault
public static bool IsEqual
调用时可显式指定:
int x = Utility.GetDefault
多数情况编译器自动推断:
var result = IsEqual("a", "b"); // T 推为 string
var found = Array.Find(new[] { 1, 2, 3 }, x => x == 2); // Find
小技巧:
• 泛型方法支持重载,但不能仅靠约束区分(如 void M
• 若参数含多个泛型类型,推断失败时需显式写出类型参数
常见约束与实用场景
约束让泛型更可控,避免运行时错误:
- where T : class —— 要求引用类型(排除 int、DateTime 等值类型)
- where T : struct —— 要求值类型(常用于高性能场景,避免装箱)
- where T : new() —— 要求有无参构造函数(可用于工厂创建对象)
- where T : IComparable —— 要求实现接口,可在方法内安全调用 CompareTo
- where TKey : notnull —— C# 8+,确保 TKey 不为 null(配合可空引用类型)
组合约束示例:
public class Repository
{
public T CreateNew() => new(); // new() 允许 new T()
public bool IsValid(T item) => item.Validate().IsValid;
}
泛型委托与常用内置泛型
.NET 提供大量泛型委托和集合,日常开发基本不用自己从头写:
-
Action
、Func —— 回调与函数抽象 -
Predicate
、Comparison —— 过滤与排序逻辑 -
List
、Dictionary 、HashSet —— 高效类型安全集合 -
IEnumerable
、IQueryable —— 支持 LINQ 查询的标准接口
例如用 Func 写一个通用转换器:
public static IEnumerable
{
foreach (var item in source) yield return selector(item);
}
调用:
var lengths = Map(new[] { "a", "bb", "ccc" }, s => s.Length); // IEnumerable
基本上就这些。泛型不是炫技工具,而是帮你把类型检查提前到编译期、减少重复代码、避开装箱拆箱的关键手段。写多了自然就顺手了。








