Casting a generic collection to base type

前端 未结 6 900
情歌与酒
情歌与酒 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.

    0 讨论(0)
  • 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<DerivedClass> list = new List<DerivedClass>();
      slice(list); //you want to do this
    }
    
    void slice(IList<BaseClass> list)
    {
      //yikes! adding OtherClass to List<DerivedClass>
      list.Add(new OtherClass());
    }
    
    0 讨论(0)
  • 2020-12-03 23:46

    If .NET 3.5 is an option, you can use the Cast<T> extension method in System.Core.dll to get a read-only IEnumerable<T> for the collection:

    using System.Linq;
    ...
    private void Refresh() {
      PopulateList( cachedCollection.Cast<cachedType>( ) );
    }
    
    0 讨论(0)
  • 2020-12-03 23:50

    This is called co-variance and while not currently supported with generics in .net, it will be added in the 4.0 framework (along with the opposite which is contra-variance).

    This excellent video from PDC 2008 is session on C# futures given by Anders Hejlsberg:

    http://channel9.msdn.com/pdc2008/TL16/

    0 讨论(0)
  • 2020-12-03 23:50

    You can cast each element into new iterator:

    var collectionOfBase = (collectionOfDerived as IEnumerable).Cast<BaseClass>();
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题