C# 泛型(Generics)是一种允许你在定义类、接口、结构体、方法或委托时使用类型参数的技术。通过泛型,你可以编写更通用的代码,同时保持类型安全性和性能。泛型的一个主要优点是它们可以减少重复代码,提高代码的复用性和灵活性。
泛型类
以下是一个简单的泛型类的例子:
public class Box<T>
{
private T item;
public Box(T item)
{
this.item = item;
}
public T Item
{
get { return item; }
set { item = value; }
}
}
在这个例子中,Box<T> 是一个泛型类,T 是类型参数。你可以用任何类型来实例化这个类:
Box<int> intBox = new Box<int>(10);
Box<string> stringBox = new Box<string>("Hello");
泛型方法
你也可以在方法中使用泛型:
public class Utility
{
public static void Print<T>(T item)
{
Console.WriteLine(item);
}
}
调用这个方法时,编译器会自动推断类型参数:
Utility.Print(10); // 输出: 10
Utility.Print("Hello"); // 输出: Hello
泛型约束
为了限制可以传递给泛型类型的类型,C# 提供了泛型约束。约束可以确保类型参数满足特定条件。常见的约束包括:
where T : class:类型必须是引用类型。where T : struct:类型必须是值类型。where T : new():类型必须有一个无参数的构造函数。where T : <base class>:类型必须是指定基类的子类。where T : <interface>:类型必须实现指定的接口。where T : U:类型必须是指定类型U或其派生类。
示例:使用多个约束
public class Box<T> where T : class, new()
{
private T item;
public Box()
{
item = new T();
}
public T Item
{
get { return item; }
set { item = value; }
}
}
在这个例子中,T 必须是引用类型并且有一个无参数的构造函数。
示例:约束为接口
public interface IMyInterface
{
void DoSomething();
}
public class MyGenericClass<T> where T : IMyInterface
{
public void Execute(T item)
{
item.DoSomething();
}
}
在这个例子中,T 必须实现 IMyInterface 接口。
泛型委托
泛型委托也非常有用,例如 Func<T, TResult> 和 Action<T>:
public class Example
{
public static void Main()
{
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(10, 20)); // 输出: 30
Action<string> print = message => Console.WriteLine(message);
print("Hello, World!"); // 输出: Hello, World!
}
}

2148

被折叠的 条评论
为什么被折叠?



