Why can't List = List?

后端 未结 5 1154
予麋鹿
予麋鹿 2020-12-12 03:03

Why won\'t the following code work?

class parent {}
class kid:parent {}

List parents=new List;

It seems obvious t

5条回答
  •  生来不讨喜
    2020-12-12 03:52

    Besides the lack of generic variance support in C# prior to version 4.0, List is mutable and so cannot safely be covariant. Consider this:

    void AddOne(List arg) where T : new()
    {
        arg.Add(new T());
    }
    
    void Whoops()
    {
        List contradiction = new List();
        AddOne(contradiction);  // what should this do?
    }
    

    This would attempt to add a Parent to a List referenced via a List reference, which is not safe. Arrays are permitted to be covariant by the runtime, but are type-checked at mutation time and an exception is thrown if the new element is not assignable to the array's runtime element type.

提交回复
热议问题