小编Dim*_*ris的帖子

字典直接访问与TryGetValue

我有一本字典,将字符串映射到这样的对象: 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 {}
Run Code Online (Sandbox Code Playgroud)

您认为首选哪种方法?第二个是更干净的编码,因为没有多余的强制转换,但是我认为它的效率比第一个低,因为它没有异常。

c# dictionary

1
推荐指数
1
解决办法
1740
查看次数

标签 统计

c# ×1

dictionary ×1