如何从不同值类型字典中通过泛型获取指定类型对象?
无需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
相关产品推荐
相关产品推荐

