ICollection not Covariant?

后端 未结 2 1056
予麋鹿
予麋鹿 2020-12-17 17:30

The purpose of this is to synchronize two collections, sender-side & receiver-side, containing a graph edge, so that when something happens (remove edge, add edge, etc)

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-17 18:17

    Eric Lippert said that C# will only support type-safe covariance and contravariance. If you would think of it, making ICollection covariant is not type-safe.

    Let's say you have

    ICollection dogList = new List();
    ICollection mammalList = dogList; //illegal but for the sake of showing, do it
    mammalList.Add(new Cat());
    

    Your mammalList (which is actually a dogList) would now then contain a Cat.

    IEnumerable is covariant because you cannot Add to it... you can only read from it -- which, in turn, preserves type-safety.

提交回复
热议问题