泛型 #
一、泛型概述 #
1.1 什么是泛型 #
泛型允许编写类型安全的可重用代码,延迟指定类型直到使用时。
1.2 泛型优势 #
- 类型安全
- 代码复用
- 性能优化
- 减少装箱拆箱
二、泛型类 #
2.1 定义泛型类 #
csharp
public class Stack<T>
{
private readonly List<T> _items = new();
public void Push(T item)
{
_items.Add(item);
}
public T Pop()
{
if (_items.Count == 0)
throw new InvalidOperationException("栈为空");
var item = _items[^1];
_items.RemoveAt(_items.Count - 1);
return item;
}
public T Peek()
{
if (_items.Count == 0)
throw new InvalidOperationException("栈为空");
return _items[^1];
}
public int Count => _items.Count;
}
var stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
int top = stack.Pop();
2.2 多类型参数 #
csharp
public class Pair<TKey, TValue>
{
public TKey Key { get; }
public TValue Value { get; }
public Pair(TKey key, TValue value)
{
Key = key;
Value = value;
}
}
var pair = new Pair<string, int>("年龄", 25);
三、泛型方法 #
3.1 定义泛型方法 #
csharp
public T Max<T>(T a, T b) where T : IComparable<T>
{
return a.CompareTo(b) > 0 ? a : b;
}
int max = Max(10, 20);
string maxStr = Max("abc", "xyz");
public void Swap<T>(ref T a, ref T b)
{
(a, b) = (b, a);
}
int x = 1, y = 2;
Swap(ref x, ref y);
3.2 泛型方法类型推断 #
csharp
public T First<T>(IEnumerable<T> items)
{
return items.First();
}
var first = First(new[] { 1, 2, 3 });
var firstStr = First(new[] { "a", "b", "c" });
四、泛型接口 #
4.1 定义泛型接口 #
csharp
public interface IRepository<T>
{
T GetById(int id);
IEnumerable<T> GetAll();
void Add(T entity);
void Update(T entity);
void Delete(int id);
}
public class UserRepository : IRepository<User>
{
public User GetById(int id) => new User { Id = id };
public IEnumerable<User> GetAll() => new List<User>();
public void Add(User entity) { }
public void Update(User entity) { }
public void Delete(int id) { }
}
4.2 协变和逆变 #
csharp
public interface IReader<out T>
{
T Read();
}
public interface IWriter<in T>
{
void Write(T value);
}
IReader<string> stringReader = new StringReader();
IReader<object> objectReader = stringReader;
IWriter<object> objectWriter = new ObjectWriter();
IWriter<string> stringWriter = objectWriter;
五、泛型约束 #
5.1 约束类型 #
| 约束 | 说明 |
|---|---|
| where T : struct | 值类型 |
| where T : class | 引用类型 |
| where T : new() | 无参构造函数 |
| where T : BaseClass | 继承自基类 |
| where T : IInterface | 实现接口 |
| where T : notnull | 非空类型 |
| where T : unmanaged | 非托管类型 |
5.2 使用约束 #
csharp
public class Repository<T> where T : class, IEntity, new()
{
public T Create()
{
return new T();
}
public T GetById(int id)
{
return default;
}
}
public interface IEntity
{
int Id { get; }
}
public class NullableHelper<T> where T : struct
{
public T? Value { get; set; }
}
public class NumberProcessor<T> where T : struct, IComparable<T>, IConvertible
{
public int Compare(T a, T b)
{
return a.CompareTo(b);
}
}
5.3 多约束 #
csharp
public class Container<T, TKey>
where T : class, IEntity, new()
where TKey : notnull
{
private readonly Dictionary<TKey, T> _items = new();
public void Add(TKey key, T item)
{
_items[key] = item;
}
public T? Get(TKey key)
{
return _items.TryGetValue(key, out var item) ? item : null;
}
}
六、泛型委托 #
6.1 泛型委托定义 #
csharp
public delegate T Transformer<T>(T input);
public T[] Transform<T>(T[] items, Transformer<T> transformer)
{
var result = new T[items.Length];
for (int i = 0; i < items.Length; i++)
{
result[i] = transformer(items[i]);
}
return result;
}
int[] numbers = { 1, 2, 3 };
int[] doubled = Transform(numbers, x => x * 2);
6.2 内置泛型委托 #
csharp
Func<int, int, int> add = (a, b) => a + b;
Action<string> print = s => Console.WriteLine(s);
Predicate<int> isEven = n => n % 2 == 0;
Func<int, bool> isPositive = n => n > 0;
七、泛型缓存 #
7.1 类型缓存 #
csharp
public static class TypeCache<T>
{
public static int Counter { get; set; }
}
TypeCache<int>.Counter = 10;
TypeCache<string>.Counter = 20;
Console.WriteLine(TypeCache<int>.Counter);
Console.WriteLine(TypeCache<string>.Counter);
八、总结 #
泛型要点:
| 要点 | 说明 |
|---|---|
| 泛型类 | class MyClass |
| 泛型方法 | T Method |
| 泛型接口 | interface IMyInterface |
| 泛型约束 | where T : constraint |
下一步,让我们学习委托!
最后更新:2026-03-26