Why can't List = List?

后端 未结 5 1155
予麋鹿
予麋鹿 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:42

    As has been pointed out, this isn't currently supported in C#. In Java, arrays are covariant, and it can cause some problems. Consider your example, the actual list should be a list of "kid", meaning all the objects in it should be "kid"s (or "grandchildren"). But if the reference you're using to access the list is a list of "parent" then you could insert a "parent" into the list which obviously shouldn't happen.

提交回复
热议问题