在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.
相关推荐
最新文章