IDictionary<,> contravariance?

前端 未结 6 738
不思量自难忘°
不思量自难忘° 2020-12-06 04:58

I have the following method in an external class

public static void DoStuffWithAnimals(IDictionary animals)

In my cal

6条回答
  •  猫巷女王i
    2020-12-06 05:49

    1. I believe what you want is called covariance, not contravariance.
    2. Classes in .Net can't be co- or contravariant, only interfaces and delegates can.
    3. IDictionary can't be covariant, because that would allow you to do something like:

      IDictionary sheep = new Dictionary();
      IDictionary animals = sheep;
      animals.Add("another innocent sheep", new Wolf());
      
    4. There is IReadOnlyDictionary in .Net 4.5. At first sight it could be covariant (the other new interface, IReadOnlyList is covariant). Unfortunately, it isn't, because it also implements IEnumerable> and KeyValuePair is not covariant.

    5. To work around this, you could make your method generic with a constraint of the type parameter:

      void DoStuffWithAnimals(IDictionary animals) where T : Animal
      

提交回复
热议问题