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

如何从不同值类型字典中通过泛型获取指定类型对象?

无需Switch的泛型字典取值实现方案

你可以通过维护一个类型与对应字典的映射表来实现,这种方式不仅避免了switch语句,还能让代码更易扩展——后续新增类型字典时,只需添加映射关系,无需修改核心的Get方法逻辑。

1. 初始化类型映射表

在类中定义一个私有字典,用来存储Type到对应字典的映射。我们可以用IDictionary<int, object>作为统一的字典接口类型,因为所有具体字典都可以向上转换为这个接口:

private readonly Dictionary<Type, IDictionary<int, object>> _dictMap;

public YourClassName()
{
    type1 = new Dictionary<int, Type1>();
    type2 = new Dictionary<int, Type2>();
    
    // 建立类型到字典的映射
    _dictMap = new Dictionary<Type, IDictionary<int, object>>
    {
        { typeof(Type1), type1 },
        { typeof(Type2), type2 }
    };
}

2. 实现泛型Get方法

在Get<T>方法中,根据泛型参数T从映射表中找到对应的字典,取值后转换为目标类型返回:

public T Get<T>(int ID)
{
    if (!_dictMap.TryGetValue(typeof(T), out var targetDict))
    {
        throw new ArgumentException($"未找到类型{typeof(T)}对应的字典");
    }

    if (!targetDict.TryGetValue(ID, out var value))
    {
        throw new KeyNotFoundException($"在{typeof(T)}字典中未找到ID为{ID}的项");
    }

    return (T)value;
}

可选优化:编译时类型安全校验

如果想避免手动注册映射时的类型错误,可以封装一个泛型注册方法,确保传入的字典类型与注册的类型匹配:

private void RegisterDict<T>(IDictionary<int, T> dict)
{
    _dictMap[typeof(T)] = dict as IDictionary<int, object>;
}

// 在构造函数中替换原有的映射初始化
public YourClassName()
{
    type1 = new Dictionary<int, Type1>();
    type2 = new Dictionary<int, Type2>();
    
    RegisterDict(type1);
    RegisterDict(type2);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 09:50:59