2010-12-11 82 views
3

假設我有一個名爲Composite的類,它包含另一個類Component的集合,所有類都具有屬性Name。使用Dictionary來存儲組件會更好嗎,還是使用動態對象更好?Dynamic vs Dictionary [C#]

例如,會是更好地做到這一點:
Component component = someComposite.Components["RandomComponent"];
或本:
Component component = someComposite.Components.RandomComponent;

凡someComposite.Components是在第二個例子中dynamic

第二種情況似乎更好,但沒有類型安全......

我想補充一點,在某些時候我最終會做這樣的:
DerivedComponent component = someComposite.Components["RandomComponent"] as DerivedComponent;
在這種情況下,dynamic可以節省我打出了轉換。

那麼哪個更好的設計?

回答

3

我要添加,在某些時候我 最終會做這樣的: DerivedComponent成分= someComposite.Components [ 「RandomComponent」]作爲 DerivedComponent;在這種情況下, dynamic可以節省我輸入 轉換。

在靜態類型的語言中,這些類型是原因;不要僅僅因爲你必須提供一些額外的語法而將它們拋出。該語法是作爲一個警告 - 「嘿!我正在做一些在這裏不是類型安全的東西!」

最後,這一切都歸結爲成本與收益。您可以擁有類型安全性,靜態調用,IDE在重構時幫助您的附加好處...或者您可以節省一些鍵入(這與文檔類似)。


此外,你必須考慮錯誤條件。隨着dynamic,您的錯誤代碼看起來像這樣,如果對象不包含定義:

try 
{ 
    var c = obj["RandomComponent"] as DerivedComponent; 
    if (c == null) 
     // deal with error... 
    return c; 
} 
catch (KeyNotFoundException) 
{ 
    // do something here... 
} 

這不會出現,你實際上是拯救自己的是:

try 
{ 
    DerivedComponent c = obj.RandomComponent; 
    return c; 
} 
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) 
{ 
    // do something here... 
} 
catch (InvalidCastException) 
{ 
    // handle error 
} 

相比很多打字。

+0

這更像是它 - 感謝解釋。 – YellPika 2010-12-11 16:57:35

6

也許這只是我,但我更多地將dynamic看作處理COM互操作以及與動態語言(如IronPython)交互的便捷方式。 dynamic不應該在全C#程序中使用。

使用Dictionary<string, Component>

並看看System.ComponentModel(即IContainerIComponent接口)。

+3

那麼,爲什麼我不應該使用動態?你已經告訴我在哪裏使用它的信息,但不是爲什麼不在別處使用它...... – YellPika 2010-12-11 03:22:56