c# - System.Collections.Generic.KeyNotFoundException 与元组键
问题描述
我有一个Tuple
像这样键入的字典:
private readonly IDictionary<Tuple<string, string>, List<Bom>> bomCache
= new Dictionary<Tuple<string, string>, List<Bom>>();
我将它用作方法的缓存:
private async Task<List<Bom>> buildActiveBoms(string materialId, string plantId) {
var key = new Tuple<string, string>(materialId, plantId);
if (!bomCache.ContainsKey(key)) {
try {
bomCache[key] = await loadList($"Bom:{materialId}:{plantId}", document => new Bom {
BomStatusId = document["BomStatusId"],
BomTypeId = document["BomTypeId"]
});
}
catch (Exception error) {
logger.Error(error);
throw;
}
}
// how, after above condition, this entry can still not exist?
try {
return bomCache.ContainsKey(key) ? bomCache[key] : new List<Bom>();
}
catch (Exception error) {
logger.Error(error);
throw;
}
}
loadList()
总是至少返回空列表,但即使是为了确保处理这个,在添加条件返回(检查ContainsKey()
)之后我仍然得到`KeyNotFoundException:
这可能是什么原因以及如何减轻这种情况?
解决方案
推荐阅读
- javascript - 有条件的 if else 列出反应中的数据
- go - 无法为 golang 设置 gitlab ci
- jaeger - jaeger 可用于跟踪端到端事务,底层组件使用轮询和回调来完成事务的步骤
- ruby-on-rails - 设计 + Sendgrid 确认 - Ruby on Rails
- python - 熊猫不读行跨度
- if-statement - 在谷歌表中索引数组时出错
- flutter - 在 Flutter 中使用 BottomNavigationBar 导航页面时的标准做法?
- java - 为独立 JavaFX 应用程序配置 USB 令牌
- visual-studio-code - 平台 IO:未定义对 `init'/[.pio\build\uno\firmware.elf] 的引用错误 1
- laravel - 请求未到达服务器(主机标头注入)