【发布时间】:2013-06-03 22:09:49
【问题描述】:
我有一个字典,它将字符串映射到这样的对象:
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 {}
您认为哪种方法更受欢迎?第二个是更干净的编码,因为没有额外的强制转换,但我认为它比第一个效率低,因为它没有异常。
【问题讨论】:
-
在字典中找不到该对象的预期行为是什么?
-
如果你知道它的含义是什么,为什么还要使用
Dictionary<string, object>而不是Dictionary<string, MyCustomType>? -
不,我可以有任何对象类型,但是有一个指定的字符串我知道值类型。例如,test 映射到 MyCustomType 对象,test1,映射到 MyCustomType2 对象。
-
那个特别的
catch { }。永远不要那样做。想都别想。 -
是的,catch {} 只是为了举例。
标签: c# dictionary