第2章 - 泛型
嗨,朋友!我是长安。
上一章我们学习了集合,这一章我们要学习泛型——让代码更通用、更安全的强大特性!
🤔 什么是泛型?
泛型允许你定义类型参数化的类、方法、接口等,在使用时再指定具体类型。
// 非泛型
class IntList
{
private int[] items;
// ...
}
class StringList
{
private string[] items;
// ...
}
// 泛型(一个类型适用所有)
class List<T>
{
private T[] items;
// ...
}
// 使用
List<int> numbers = new List<int>();
List<string> names = new List<string>();
🌟 泛型的优势
- 类型安全:编译时检查类型
- 代码复用:一套代码适用多种类型
- 性能更好:避免装箱拆箱
💡 泛型方法
static T GetMax<T>(T a, T b) where T : IComparable<T>
{
return a.CompareTo(b) > 0 ? a : b;
}
// 使用
int maxInt = GetMax(5, 10); // 10
string maxStr = GetMax("abc", "xyz"); // "xyz"
📝 本章小结
- 泛型提高代码复用性和类型安全
- 使用
<T>定义类型参数 - 泛型类、泛型方法、泛型接口
- 泛型约束限制类型参数
