C#泛型通过类型参数化实现类型安全与代码复用,允许定义泛型类、方法和接口,避免装箱拆箱提升性能,并通过where约束确保类型特定操作的编译时安全性。

C# 的泛型,简单来说,就是一种编写可以处理多种数据类型,同时又保持类型安全的代码的方式。它允许你定义类、接口和方法,这些成员在声明时并不指定具体的数据类型,而是在使用时才指定。这就像是制作一个通用的模具,你可以用它来生产不同材质(不同类型)的产品,而不用为每种材质都重新设计一个模具。它解决了在保证代码复用性的同时,避免了传统
object
泛型是C#语言中一个非常强大的特性,它在.NET Framework 2.0中被引入,彻底改变了我们编写可重用和类型安全代码的方式。在我看来,它简直是现代C#开发不可或缺的基石。在泛型出现之前,如果你想写一个能处理任何类型数据的集合,比如一个列表,你很可能会用到
System.Collections.ArrayList
ArrayList
object
int
泛型完美地解决了这个问题。它允许你创建一个“类型参数化”的结构,比如
List<T>
T
List<int>
int
int
从我个人的开发经验来看,泛型不仅仅是语法糖,它从根本上改变了我们对“通用代码”的理解和实践。过去,为了实现通用性,我们可能会选择两种极端方式:一种是使用
object
首先,类型安全是泛型最直接的贡献。想象一下,你有一个方法,它需要处理不同类型的数值,但你又想确保传入的都是可以进行加法运算的类型。如果用
object
is
as
GenericCalculator<T>
T
T
IAdditionCapable<T>
其次,性能提升对于处理大量值类型数据尤其重要。装箱和拆箱操作会涉及内存分配和类型转换,这在循环中频繁发生时,性能开销是相当可观的。泛型避免了这些不必要的开销。例如,一个
List<int>
int
object
再者,代码复用性得到了质的飞跃。你可以编写一个通用的排序算法,一个通用的数据结构(栈、队列、字典),或者一个通用的数据访问层,而无需关心具体的数据类型。只需要定义一次,就能在各种场景下重用。这不仅仅是减少了代码量,更重要的是,它提高了代码的可维护性和可扩展性。当我需要支持一种新的数据类型时,通常只需要修改一小部分代码,而不是重写整个模块。这种感觉,就像拥有了一把万能钥匙。
在C#中,泛型的应用场景非常广泛,主要体现在泛型类、泛型接口和泛型方法上。理解这些基本用法,是掌握泛型的第一步。
1. 泛型类 (Generic Classes)
泛型类允许你定义一个类,它的某些成员(字段、属性、方法)操作的数据类型是可变的。最经典的例子就是
List<T>
Dictionary<TKey, TValue>
// 定义一个简单的泛型盒子类
public class GenericBox<T>
{
private T _content; // 存储任意类型的内容
public GenericBox(T content)
{
_content = content;
}
public T GetContent()
{
return _content;
}
public void SetContent(T newContent)
{
_content = newContent;
}
public void DisplayContentType()
{
Console.WriteLine($"Box contains type: {_content.GetType().Name}");
}
}
// 如何使用泛型类
// 存储一个整数
GenericBox<int> intBox = new GenericBox<int>(123);
Console.WriteLine($"Int Box Content: {intBox.GetContent()}"); // 输出: Int Box Content: 123
intBox.DisplayContentType(); // 输出: Box contains type: Int32
// 存储一个字符串
GenericBox<string> stringBox = new GenericBox<string>("Hello Generics!");
Console.WriteLine($"String Box Content: {stringBox.GetContent()}"); // 输出: String Box Content: Hello Generics!
stringBox.DisplayContentType(); // 输出: Box contains type: String
// 尝试将字符串放入整数盒子(编译时错误!)
// intBox.SetContent("Oops"); // 这行代码会引发编译错误,因为它期望一个 int在
GenericBox<T>
T
GenericBox<int>
T
int
GenericBox<string>
T
string
2. 泛型方法 (Generic Methods)
泛型方法允许你定义一个方法,它的一个或多个参数类型、返回类型,或者局部变量类型是可变的。这在编写通用工具方法时非常有用。
public class Utility
{
// 定义一个泛型方法,用于交换两个变量的值
public static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
// 另一个泛型方法,用于比较两个值是否相等
public static bool AreEqual<T>(T value1, T value2)
{
// 对于引用类型,默认的Equals方法会比较引用;
// 对于值类型,会比较值。
// 对于自定义类型,需要重写Equals方法。
return value1.Equals(value2);
}
}
// 如何使用泛型方法
int num1 = 10, num2 = 20;
Console.WriteLine($"Before swap: num1={num1}, num2={num2}"); // 输出: Before swap: num1=10, num2=20
Utility.Swap(ref num1, ref num2); // 编译器会自动推断 T 为 int
Console.WriteLine($"After swap: num1={num1}, num2={num2}"); // 输出: After swap: num1=20, num2=10
string str1 = "Apple", str2 = "Banana";
Console.WriteLine($"Before swap: str1={str1}, str2={str2}"); // 输出: Before swap: str1=Apple, str2=Banana
Utility.Swap(ref str1, ref str2); // 编译器会自动推断 T 为 string
Console.WriteLine($"After swap: str1={str1}, str2={str2}"); // Output: After swap: str1=Banana, str2=Apple
Console.WriteLine($"Are 5 and 5 equal? {Utility.AreEqual(5, 5)}"); // 输出: True
Console.WriteLine($"Are 'hello' and 'world' equal? {Utility.AreEqual("hello", "world")}"); // 输出: False泛型方法通常非常简洁,并且编译器在调用时通常能够自动推断出类型参数
T
泛型约束是我认为泛型特性中,真正让它变得强大和实用的地方。如果没有约束,泛型类型参数
T
object
Equals()
ToString()
T
T
T
泛型约束通过
where
T
T
T
常见的泛型约束类型:
where T : class
T
public void ProcessReferenceType<T>(T item) where T : class { /* ... */ }int
struct
where T : struct
T
Nullable<T>
public void ProcessValueType<T>(T item) where T : struct { /* ... */ }string
object
where T : new()
T
public T CreateInstance<T>() where T : new() { return new T(); }T
where T : BaseClass
T
BaseClass
public void ProcessDerivedType<T>(T item) where T : Animal { item.Walk(); }BaseClass
where T : IInterface
T
IInterface
public void SortCollection<T>(List<T> list) where T : IComparable<T> { list.Sort(); }IComparable<T>
CompareTo
where T : U
T
U
public void CopyFrom<T, U>(T source, U destination) where T : U { /* ... */ }为什么需要它们?
没有约束,你无法在泛型方法内部对
T
object
T
CompareTo
object
CompareTo
T
IComparable<T>
public class GenericSorter
{
// 这是一个没有约束的泛型方法,无法直接比较T
// public static T GetMax<T>(T a, T b)
// {
// // 编译错误:'T' 不包含 'CompareTo' 的定义
// if (a.CompareTo(b) > 0) return a;
// return b;
// }
// 使用 IComparable<T> 约束,允许比较
public static T GetMax<T>(T a, T b) where T : IComparable<T>
{
if (a.CompareTo(b) > 0)
{
return a;
}
return b;
}
// 使用 new() 约束,允许创建实例
public static T CreateAndInitialize<T>() where T : new()
{
T instance = new T();
// 假设T有一个名为Initialize的公共方法,但这里还需要接口约束
// instance.Initialize();
return instance;
}
}
// 使用示例
int maxInt = GenericSorter.GetMax(5, 10); // maxInt = 10
string maxString = GenericSorter.GetMax("apple", "banana"); // maxString = "banana"
// 假设我们有一个 Person 类,它实现了无参数构造函数
public class Person
{
public string Name { get; set; } = "Unknown";
public Person() { }
public Person(string name) { Name = name; }
}
Person newPerson = GenericSorter.CreateAndInitialize<Person>();
Console.WriteLine($"New person's name: {newPerson.Name}"); // 输出: New person's name: Unknown泛型约束让你的泛型代码从“万能”变得“有条件万能”,它在编译时就提供了强大的类型检查,确保了代码的正确性和可靠性。这对于编写可重用且健壮的库代码来说,是不可或缺的工具。可以说,没有泛型约束,泛型的实用性会大打折扣。
以上就是C#的泛型是什么?如何使用?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号