I have the following method in an external class
public static void DoStuffWithAnimals(IDictionary<string, Animal> animals)
In my calling code, I already have a Dictionary<string, Lion>
object, but I can't pass this in as this method's argument. So a IDictionary<,>
isn't contravariant? I can't see any reason why this shouldn't work.
The only solution I can think of is:
var animals = new Dictionary<string, Animal>();
foreach(var kvp in lions) {
animals.Add(kvp.Key, kvp.Value);
}
Is there no way to pass this dictionary into this method, without having to create a new dictionary of the same objects?
EDIT:
As it's my method, I know that the only member I'm using from the dictionary is the getter of TValue this[TKey key]
, which is a member of IDictionary<TKey, TValue>
, so in this scenario, I'm unable to use a 'wider' type for the parameter.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…