Casting a generic collection to base type

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

    I don't think it's possible, and indeed it shouldn't be:

    class BaseClass {}
    class DerivedClass : BaseClass {}
    class OtherClass : BaseClass {}
    
    void test()
    {
      List list = new List();
      slice(list); //you want to do this
    }
    
    void slice(IList list)
    {
      //yikes! adding OtherClass to List
      list.Add(new OtherClass());
    }
    

提交回复
热议问题