Casting a generic collection to base type

前端 未结 6 921
情歌与酒
情歌与酒 2020-12-03 22:46

I\'ve got an IList that I want to cast to ICollection but when I attempt an explicit cast, I get null

6条回答
  •  悲哀的现实
    2020-12-03 23:33

    The short answer is "No." You would need to create a new collection with the new BaseClass type and populate it.

    If you think about it, it makes sense. If you could simply "cast" your collection to BaseClass, you could then stick something that was of type "BaseClass" into it, thereby forcing a simple BaseClass object into a DerivedClass Collection. This would defeat the purpose creating a Collection with Type-Safety.

    In the extreme case, if you had two derived classes, Foo and Bar, you could force Bar objects into a collection of Foo objects by type-casting the collection back to a collection of BaseClass.

提交回复
热议问题