我有一個映射字符串對象像這樣的詞典: Dictionary<string, object> myDic;
字典直接訪問VS TryGetValue
之前我知道什麼對象的類型是基於字符串,但我的問題是我是否應該使用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 {}
你覺得用什麼方法最好?第二個是更乾淨的編碼,因爲沒有額外的鑄件,但我認爲它比第一個效率低,因爲它是無異常的。
預期的行爲是什麼是在字典中找不到對象? – vcsjones
如果你知道這意味着什麼,你將如何使用'Dictionary'而不是'Dictionary '? –
不,我可以有任何對象類型,但有一個指定的字符串,我知道值類型。例如,測試映射到MyCustomType對象test1,映射到MyCustomType2對象。 –