Casting a generic collection to base type

前端 未结 6 923
情歌与酒
情歌与酒 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:52

    Switching between generic containers of derived classes and base classes is not supported. (It does work with arrays) It is possible to write a type converter to reasonably cleanly perform the switch without manually copying elements between the lists.

    Check out this link for a description of the issue/limitation and a solution: http://www.25hoursaday.com/weblog/CommentView.aspx?guid=AF7AA888-A227-454C-8687-71FA77186064

    Down at the bottom is a nice generic-enabled version.

提交回复
热议问题