C# Generics Inheritance Problem

前端 未结 5 545
囚心锁ツ
囚心锁ツ 2020-12-09 19:24

I\'d like to add different types of objects derived from one class with generics into a List of base type. I get this compile error

Error   2   Argument 1: c         


        
5条回答
  •  北荒
    北荒 (楼主)
    2020-12-09 20:03

    You can do this using covariance and contravariance, but your ShelterBase class needs to derive from an interface, since only interfaces can be co- or contravariant. You list will need to be a List> and it should work.

    See here for more info

提交回复
热议问题