IDictionary<,> contravariance?

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

I have the following method in an external class

public static void DoStuffWithAnimals(IDictionary animals)

In my cal

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-06 05:30

    Firstly, covariance and contravariance in C# only apply to interfaces and delegates.

    So your question is really about IDictionary.

    With that out of the way, it's simplest to just remember that an interface can only be co/contra-variant if all values of a type parameter are either only passed in, or only passed out.

    For example (contravariance):

    interface IReceiver // note 'in' modifier
    {
        void Add(T item);
        void Remove(T item);
    }
    

    And (covariance):

    interface IGiver // note 'out' modifier
    {
        T Get(int index);
        T RemoveAt(int index);
    }
    

    In the case of IDictionary, both type parameters are used in both an in and out capacity, meaning that the interface cannot be covariant or contravariant. It is invariant.

    However, the class Dictionary does implement IEnumerable which is covariant.

    A great reference for this is:

    https://docs.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance

提交回复
热议问题