我有以下方法在外部類IDictionary <,>逆變?
public static void DoStuffWithAnimals(IDictionary<string, Animal> animals)
在我的呼喚代碼,我已經有一個Dictionary<string, Lion>
對象,但我不能接受這一點,因爲這方法的參數。所以IDictionary<,>
不是逆變?我不明白爲什麼這不應該工作。
我能想到的唯一的解決辦法是:
var animals = new Dictionary<string, Animal>();
foreach(var kvp in lions) {
animals.Add(kvp.Key, kvp.Value);
}
有沒有辦法通過這本詞典進入這個方法,而無需創建同一對象的一個新的字典?
編輯:
由於這是我的方法,我知道,我是從字典中使用的唯一成員是TValue this[TKey key]
的getter,它是IDictionary<TKey, TValue>
一員,所以在這種情況下,我無法使用「更寬」類型的參數。
IDictionary的似乎是不變的。其聲明不包含進/出細節。 –