52、C# 泛型 (Generics)

泛型是 C# 2.0 引入的一项强大功能,它允许你编写可以处理多种数据类型的代码,而无需为每种类型重复编写相同的逻辑。泛型提高了代码的重用性、类型安全性和性能。

基本概念

泛型类

csharp 复制代码
public class GenericClass<T>
{
    private T _value;
    
    public GenericClass(T value)
    {
        _value = value;
    }
    
    public T GetValue()
    {
        return _value;
    }
}

// 使用示例
var intClass = new GenericClass<int>(42);
var stringClass = new GenericClass<string>("Hello");

泛型方法

csharp 复制代码
public class Utility
{
    public static T Max<T>(T a, T b) where T : IComparable<T>
    {
        return a.CompareTo(b) > 0 ? a : b;
    }
}

// 使用示例
int maxInt = Utility.Max(10, 20);
string maxString = Utility.Max("apple", "orange");

泛型约束

泛型约束用于限制类型参数可以使用的类型:

csharp 复制代码
public class ConstrainedClass<T> where T : class, new()
{
    // T 必须是引用类型且有无参构造函数
}

常见的约束类型:

  • where T : class - T 必须是引用类型
  • where T : struct - T 必须是值类型
  • where T : new() - T 必须有无参构造函数
  • where T : IComparable - T 必须实现特定接口
  • where T : BaseClass - T 必须继承自特定基类

泛型接口和委托

泛型接口

csharp 复制代码
public interface IRepository<T>
{
    T GetById(int id);
    void Add(T entity);
}

public class SqlRepository<T> : IRepository<T>
{
    // 实现...
}

泛型委托

csharp 复制代码
public delegate T Processor<T>(T item);

// 使用示例
Processor<int> square = x => x * x;
int result = square(5); // 25

泛型与性能

泛型提供了类型安全性,同时避免了装箱和拆箱操作,提高了性能:

csharp 复制代码
// 非泛型版本(有装箱拆箱开销)
ArrayList list = new ArrayList();
list.Add(42); // 装箱
int value = (int)list[0]; // 拆箱

// 泛型版本(无装箱拆箱)
List<int> genericList = new List<int>();
genericList.Add(42); // 无装箱
int genericValue = genericList[0]; // 无拆箱

协变和逆变

C# 4.0 引入了协变(covariance)和逆变(contravariance):

csharp 复制代码
// 协变 - out 关键字
public interface IEnumerable<out T> : IEnumerable
{
    IEnumerator<T> GetEnumerator();
}

// 逆变 - in 关键字
public interface IComparer<in T>
{
    int Compare(T x, T y);
}

实际应用示例

csharp 复制代码
// 泛型缓存类
public class Cache<TKey, TValue>
{
    private readonly Dictionary<TKey, TValue> _cache = new Dictionary<TKey, TValue>();
    
    public void Add(TKey key, TValue value)
    {
        _cache[key] = value;
    }
    
    public bool TryGet(TKey key, out TValue value)
    {
        return _cache.TryGetValue(key, out value);
    }
}

// 使用示例
var userCache = new Cache<int, string>();
userCache.Add(1, "Alice");
userCache.Add(2, "Bob");

泛型是 C# 中非常强大的特性,合理使用可以显著提高代码的质量和可维护性。

相关推荐
小黄人软件3 小时前
OpenSSL 与 C++ 搭建一个支持 TLS 1.3 的服务器
服务器·开发语言·c++
武昌库里写JAVA4 小时前
Vue3编译器:静态提升原理
java·开发语言·spring boot·学习·课程设计
编程乐趣4 小时前
推荐一个Excel与实体映射导入导出的C#开源库
开源·c#·.net·excel
日晞4 小时前
深浅拷贝?
开发语言·前端·javascript
大模型铲屎官4 小时前
【深度学习-Day 16】梯度下降法 - 如何让模型自动变聪明?
开发语言·人工智能·pytorch·python·深度学习·llm·梯度下降
明月看潮生4 小时前
青少年编程与数学 02-020 C#程序设计基础 05课题、数据类型
开发语言·青少年编程·c#·编程与数学
沐土Arvin5 小时前
性能优化关键:link、script和meta的正确打开方式
开发语言·前端·javascript·设计模式·性能优化·html
CoderIsArt5 小时前
功能“递归模式”在 C# 7.3 中不可用,请使用 8.0 或更高的语言版本的一种兼容处理方案
c#
zhangfeng11335 小时前
Python 和 matplotlib 保存图像时,确保图像的分辨率和像素符合特定要求(如 64x64),批量保存 不溢出内存
开发语言·python·matplotlib
leo__5205 小时前
matlab实现激光腔长计算满足热透镜效应
开发语言·matlab