如果我总是用TryGetValue访问.NET字典? [英] Should I always use TryGetValue to access .net Dictionaries?

查看:98
本文介绍了如果我总是用TryGetValue访问.NET字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在<一个href="http://stackoverflow.com/questions/886814/why-doesnt-net-provide-us-with-the-key-when-it-raises-a-keynotfound-exception">another SO问题,我见过几个人建议我总是使用TryGetValue。

In another SO question, I've seen several people recommend me to always use TryGetValue.

虽然我总是用TryGetValue在包含?/访问模式,我避免在目的这个模式时,我希望的关键,始终处于字典。然后,我去一个直接索引器访问,让就抛出一个异常,如果该键不存在,因为意想不到的事情真的发生了(即重点不是在字典中,而我希望它)。

While I always use TryGetValue over the Contains?/Access pattern, I avoid this pattern on purpose when I expect the key to always be in the dictionary. I then go for a direct indexer access, so that an exception is raised if the key isn't there, because something unexpected really happened (i.e. the key wasn't in the dictionary while I expect it to).

由于好像是对我的最佳实践一个普遍的共识(四分之三的人对我所提到的明确建议使用TryGetValue在所有的时间后),我渴望去阅读上的进一步讨论话题...

Since there seems to be a general consensus against my "best-practice" (3 out of 4 people on the post I mentioned explicitly advised to use TryGetValue at all time), I'm eager to read an extended discussion on that topic...

推荐答案

没有,你是完全正确IMO。

No, you're entirely right IMO.

有这样做没有意义的:

if (dict.TryGetValue(key, out value))
{
    // whatever
}
else
{
    throw new SomeException("key '" + key + "' wasn't in dictionary");
}

的唯一好处,超过:

The only benefit of that over:

value = dict[key];

是,你得到一个更加明确的异常消息......但是可读性的成本,海事组织。

is that you get a more explicit exception message... but at the cost of readability, IMO.

这就像铸造VS使用 - 异常是一个正确的结果,当状态是错误的,所以用它给出的行为形式

It's like casting vs using as - an exception is the right result when the state is "wrong", so use the form which gives that behaviour.

这篇关于如果我总是用TryGetValue访问.NET字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆