gpt4 book ai didi

c# - 为什么 .net 在引发 KeyNotFound 异常时不向我们提供 key (我怎样才能得到它?)

转载 作者:太空狗 更新时间:2023-10-30 00:59:14 25 4
gpt4 key购买 nike

当您尝试访问不在字典中的键时(例如),这是您获得的堆栈跟踪:

   at System.ThrowHelper.ThrowKeyNotFoundException()
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
.... .... (my own code stack trace)

就像大多数人可能做的那样,我会在这些错误发生时记录下来,并尝试弄清楚发生了什么。

我想要的两个关键信息是这是在哪里发生的(堆栈跟踪对此非常有帮助),以及导致异常的关键,它没有出现在任何地方。

要么我没有正确查看(KeyNotFoundException 类包含一个“Data”成员,它始终为空,“Message”字段不包含键值),要么它没有包含在框架。

我无法想象 .net BCL 团队中没有人认为这是一个有用的功能。我很好奇他们为什么不包括它。有什么好的理由不这样做吗?

您如何处理这些异常?我能想到的唯一选择是在 Dictionary 上使用自定义扩展方法,该方法将包装调用、捕获异常并使用有关 key 的其他信息重新抛出它,但这对我不拥有的代码没有帮助,更改这样的“基本”功能感觉很糟糕。

你怎么看?


我知道 this question ,关于无法访问引发异常的方法的参数这一一般事实。我的问题与 KeyNotFoundException 特别相关。


编辑:我知道 TryGetValue 模式,当我希望我的集合可能不包含 key 时,我总是这样做。但是当它应该包含它时,我不测试,因为我更希望我的程序因异常而失败,这样我就知道 之前 发生了意想不到的事情(即应该插入 key 的时间)

我可以用 try/catch/log error/rethrow 包裹我所有的字典访问,但​​这会导致难以阅读的代码,并与我所有的异常处理/日志记录杂乱无章。

最佳答案

为什么要依赖(缓慢的)异常?只需使用 ContainsKeyTryGetValue 验证 key 是否存在?

我不知道异常不包含导致错误的字段的原因(可能是因为它应该是非通用的),但如果您认为需要它,就将其包装起来。

class ParameterizedKeyNotFoundException<T> : KeyNotFoundException {
public T InvalidKey { get; private set; }

public ParameterizedKeyNotFoundException(T InvalidKey) {
this.InvalidKey = InvalidKey;
}
}

static class Program {

static TValue Get<TKey, TValue>(this IDictionary<TKey, TValue> Dict, TKey Key) {
TValue res;

if (Dict.TryGetValue(Key, out res))
return res;

throw new ParameterizedKeyNotFoundException<TKey>(Key);
}

static void Main(string[] args) {

var x = new Dictionary<string, int>();

x.Add("foo", 42);

try {
Console.WriteLine(x.Get("foo"));
Console.WriteLine(x.Get("bar"));
}
catch (ParameterizedKeyNotFoundException<string> e) {
Console.WriteLine("Invalid key: {0}", e.InvalidKey);
}

Console.ReadKey();
}
}

关于c# - 为什么 .net 在引发 KeyNotFound 异常时不向我们提供 key (我怎样才能得到它?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/886814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com