当抛出 KeyNotFoundException 时,如何查看未找到哪个键?
System.Collections.Generic.Dictionary
抛出 KeyNotFoundException
,但我看不到哪个键应该丢失。我如何确定这一点?
A System.Collections.Generic.Dictionary
is throwing KeyNotFoundException
, but I can't see which key is supposedly missing. How do I determine this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
自定义异常:
方便的扩展方法:
用法:
Custom exception:
Handy extension method:
Usage:
没有办法从异常中看出这一点。您需要为此实施自己的解决方案。
There is no way to tell this from the exception. You need to implement your own solution for this.
如果您可以自定义声明字典的实现,则可以轻松地用自定义类型替换 System.Collections.Generic.Dictionary,并引发更好的 KeyNotFoundException。虽然这与 abatishchev 的答案类似,但我不喜欢他引入的扩展方法,因为这意味着我们有两种不同的方法来实现完全相同的事情。如果可能的话应该避免这种情况。我通过使用“NiceDictionary”解决了这个问题,它可以像用作基类的原始 Dictinary 一样使用。实现几乎是微不足道的:
如上所述,您可以像使用原始字典一样精确地使用它。由于覆盖了数组运算符([]),它神奇地工作了。
If it is possible for you to customize the implementation where the dictionary is declared, you can easily replace System.Collections.Generic.Dictionary by a custom type throwing a nicer KeyNotFoundException. While this is similar to the answer of abatishchev, I don't like the extension method he introduced, since it means that we have two different ways to achieve the exactly same thing. This should be avoided if possible. I solved the problem by using a "NiceDictionary" instead, which can be used exactly like the original Dictinary used as base class. The implementation is almost trivial:
As said, you can use it exaclty as you would use the original Dictionary. It magically works because of the overridden array operator ([]).
你不能仅仅通过查看异常来判断。当抛出异常时,您必须中断调试器(Visual Studio 中的“调试 -> 异常...”)并查看访问了哪个键。或者,您可以捕获代码中的异常并将其打印出来(例如打印到控制台)。
You can't just by looking at the exception. You will have to break into the debugger when the exception is thrown (Debug -> Exceptions... in Visual Studio) and see what key has been accessed. Alternatively you could catch the exception in code and print it out (e.g. to the console).
使用调试器(如果需要,检查 Debug->Exceptions 中的 ThrowOnCatch)并查看
use the debuger (if needed check the ThrowOnCatch in Debug->Exceptions) and have a look
我使用了这个扩展方法
I used this extension method
你会认为他们可以将尝试的密钥添加到异常中。
这就是我所做的
you would think that they could add the attempted key to the exception.data
this is what i did
System.Collections.Generic.KeyNotFoundException 已抛出
如果您将 DotNet Core 与 Xamarin Studio 一起使用并且收到此错误,您可以检查密钥是否存在并满足以下条件:
System.Collections.Generic.KeyNotFoundException has been thrown
If you are using DotNet Core with Xamarin Studio and you get this error you can check if the key exists with the following condition: