首页 > 解决方案 > 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:

调试会话

这可能是什么原因以及如何减轻这种情况?

标签: c#

解决方案


推荐阅读