简体   繁体   中英

c# collection inheritance

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?

For example:

HashSet<animal> animals = new HashSet<animal>();
HashSet<dog> dogs = new HashSet<dog>();
animals.also_appears_to_include(dogs);

So if I for example added 2 elements to dogs and 1 to animals, then looked at how many elements animals has I would see 3.

Alternatively I could put references to the above mentioned 3 elements in each, giving animals 3 elements and dogs 2. I'd still have the two separate, overlapping lists which is desirable, however adding and removing elements could become tricky, in this simple example having to add or remove from both collections in the case of adding and removing dogs.

Or I could implement my own collection with this functionality.

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>();

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>

Thats not that tricky

// Adding 
Animals.Add( animal );
if( animal is dog )
    Dogs.Add( animal );

//Removing 
Dogs.Remove( animal );
Animals.Remove( animal );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM