c# collection inheritance

前端 未结 3 648
忘掉有多难
忘掉有多难 2021-01-14 23:53

Is there a collection in c# that supports the inheritance like concept that objects can have of appearing to include all the elements from another as well as themselves?

相关标签:
3条回答
  • 2021-01-15 00:03

    Thats not that tricky

    // Adding 
    Animals.Add( animal );
    if( animal is dog )
        Dogs.Add( animal );
    
    //Removing 
    Dogs.Remove( animal );
    Animals.Remove( animal );
    
    0 讨论(0)
  • 2021-01-15 00:06

    There is nothing provided by MS that can achieve your functionality, however

    You could just keep a set of animal and use linq to filter it on the fly:

    var animals = new HashSet<Animal>();
    var dogs = animals.OfType<Dog>();
    
    0 讨论(0)
  • 2021-01-15 00:23

    Let dogs and cats inherit from an interface, and create HashSet's of the interface instead of the classes. Or use a base class.

    for example:

    HashSet<IAnimal>
    
    0 讨论(0)
提交回复
热议问题