我有它可以在幾個不同類型的對象的集合運作,對他們採取適當行動的靜態方法的類:如何處理一個IDictionary只有強類型的鍵?
static void DoSomething(ICollection<TypeA> things)
{
// Do something with TypeA elements
}
static void DoSomething(ICollection<TypeB> things)
{
// Do something with TypeB elements
}
其他地方在我的代碼有很多,其使用兩種TypeA
字典或TypeB
爲他們的鑰匙,併爲他們的價值觀的各種類型。我最後撥打了DoSomething(dictionary.Keys)
,我認爲接受dictionary
並將.Keys
集合傳遞給適當的過載的方法會更好。
看來我可以做到這一點,如果我強類型的字典:
static void DoSomething(IDictionary<TypeA,object> dictionary)
{
DoSomething(dictionary.Keys);
}
但後來我需要爲每個IDictionary<TypeA,TValues>
,它可能會遇到過載,即使該方法不需要知道什麼TValues
是工作。
或者我似乎能夠接受一個通用IDictionary
,但隨後不得不重鑄Keys
到合適的類型:
static void DoSomething(IDictionary dictionary)
{
DoSomething((ICollection<TypeA>) dictionary.Keys);
}
這似乎並不明智,因爲使用字典不支持的關鍵類型的呼叫贏得」翻譯編譯器,我大概不得不依靠Reflection來選擇正確的過載。
我錯過了一個更好的選擇嗎?
確實typeA和typeB共享一個接口或基類?你可以使用泛型 –
你介意使用'dynamic'嗎? static void DoSomething(IDictionary dictionary)' –
Quantic
我剛試過這個,解釋器似乎沒有識別到對這樣聲明的方法的調用。所述「不能從IDictionary'轉換爲'ICollection '」 - 即試圖將它傳遞給不同的過載。我對「動態」不熟悉 - 聲明或調用是否需要滿足其他條件? –
Will