字典直接访问与TryGetValue [英] Dictionary Direct access vs TryGetValue
问题描述
我有一个字典,它将字符串映射到这样的对象:
Dictionary<string, object> myDic;
I have a dictionary which maps strings to objects like this:
Dictionary<string, object> myDic;
我事先知道对象的类型是基于字符串的,但是我的问题是我应该使用TryGetValue还是使用try,catch语句直接查找.
I know prior what the type of the object is based on the string, but my question is whether I should use TryGetValue, or direct lookups with try, catch statements.
示例:
//TryGetValueMethod
object myObject = null;
myDic.TryGetValue("test", out myObject);
MyCustomType t1 = (MyCustomType) myObject;
//Direct lookup method
try
{
MyCustomType t2 = (MyCustomType) myDic["test"];
//Do something here...
} catch {}
您认为首选哪种方法?第二个是更干净的编码,因为没有多余的强制转换,但是我认为它的效率比第一个低,因为它没有异常.
What method do you think is preferred? The second one is more clean coding because there are no extra castings, but i think it is less efficient than the first, because it is exception-free.
推荐答案
我不认为您应该使用try
/catch
来形成这样的逻辑路径. Exception
应该是例外情况,其中某些地方出了错".
I don't think you should use try
/catch
to form a logical path like that. Exception
s are supposed to be exceptional cases, where something has "gone wrong".
我个人更喜欢ContainsKey
:
if (myDic.ContainsKey("test")) {
MyCustomType value = myDic["test"];
// do something with the value
}
如果您认为未找到密钥意味着某事出错",那么我将省略测试,并在找不到密钥的情况下抛出异常.
If you think that not finding the key means that something has "gone wrong", then I would omit the test, and let an exception be thrown if the key is not found.
这些天来,我尝试改用TryGetValue
.有点笨拙,但是一旦您习惯了它,还算不错.
these days I try to use TryGetValue
instead. It's slightly more clumsy, but once you get used to it, it's not so bad.
MyCustomType value;
if (myDic.TryGetValue("test", out value)) {
// do something with value
}
现在,在out var
中,我肯定会更多地使用TryGetValue
.类似地,您可以编写一个CantGetValue
方法(具有相反的布尔结果的方法),因为在大多数情况下,您想要在没有的情况下(而不是在没有值的情况下)做一些额外的事情. /p>
Now with out var
I definitely use TryGetValue
a lot more. Similarly you can write a CantGetValue
method (same thing with opposite boolean result), since most of the time you want to do something extra when there isn't a value, not when there is.
if (dict.TryGetValue("test", out var value)) {
// do something with value
}
// or
if (cache.CantGetValue("test", out var cachedValue)) {
// cache value
}
// make use of value
这篇关于字典直接访问与TryGetValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!