You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现方法重载时如何避免代码重复?

如何避免Dictionary键类型不同时的方法重载重复代码?

你可以通过泛型方法消除这类重复代码,因为两个重载的核心逻辑完全一致,仅键的类型存在差异。泛型能让方法适配任意符合Dictionary键要求的类型,同时保留统一的逻辑实现。

泛型实现代码

private bool CheckNotification<TKey>(Dictionary<TKey, DateTime> dict, TKey key, int duration)
    where TKey : notnull
{
    return !dict.ContainsKey(key) || (DateTime.Now - dict[key]).TotalSeconds >= duration;
}

关键说明

  • TKey是泛型类型参数,代表Dictionary的键类型,它可以是string、int,也可以是任何其他可作为Dictionary键的类型(比如Guid、long等)。
  • where TKey : notnull约束是必须的:因为Dictionary的键不允许为null,添加这个约束能在编译阶段确保传入的键类型符合要求,避免潜在的运行时错误和编译警告。

使用方式

原本的两种场景都可以直接调用这个泛型方法,无需额外编写重载:

  • 处理string类型键的Dictionary:
    var stringDict = new Dictionary<string, DateTime>();
    bool result1 = CheckNotification(stringDict, "user1", 300);
    
  • 处理int类型键的Dictionary:
    var intDict = new Dictionary<int, DateTime>();
    bool result2 = CheckNotification(intDict, 1001, 300);
    

这种方式不仅消除了代码重复,还让方法具备更好的扩展性——后续如果需要支持其他键类型,无需修改或新增方法,直接调用即可。

内容的提问来源于stack exchange,提问作者rkr87

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 01:35:07