我有一个将字符串映射到这样的对象的字典:
Dictionary<string, object> myDic;
我之前知道对象的类型是基于字符串的,但我的问题是我是应该使用TryGetValue,还是使用try,catch语句直接查找。
示例:
//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 {}
您认为哪种方法更受青睐?第二个是更干净的编码,因为没有额外的铸件,但我认为它的效率低于第一个,因为它没有例外。
答案 0 :(得分:5)
MSDN说“使用此方法[TryGetValue]比捕获Item属性抛出的KeyNotFoundException更有效。”
它还解释了TryGetValue
“结合了ContainsKey
方法和Item属性”的功能..
您还应该只捕获该特定异常,而不是所有异常。
更新:从C#7开始,您现在可以写道:
if (myDic.TryGetValue("test", out MyCustomType value)) {
// do something with value
}
答案 1 :(得分:3)
我认为您不应该使用try
/ catch
来形成这样的逻辑路径。 Exception
应该是例外情况,其中某些事情“出错”。
就个人而言,我更喜欢ContainsKey
:
if (myDic.ContainsKey("test")) {
MyCustomType value = myDic["test"];
// do something with the value
}
如果您认为找不到密钥意味着某些内容“出错”,那么我会省略测试,如果找不到密钥则抛出异常。
编辑:这些天我尝试使用TryGetValue
代替。它稍微笨拙,但是一旦你习惯它,它就不那么糟了。
MyCustomType value;
if (myDic.TryGetValue("test", out value)) {
// do something with value
}
答案 2 :(得分:0)
如果您可以安全地预测密钥应该始终存在,那么将其包装在Try ... Catch中。这样,只有在出现问题时才会抛出异常。
TryGetValue
是一个更好的选择 - Dictionary.ContainsKey(key)
同样出色 - 最终它与幕后的TryGetValue
做同样的事情。