c# collection inheritance

安稳与你 提交于 2019-12-30 11:43:07

问题


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.


回答1:


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



回答2:


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>



回答3:


Thats not that tricky

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

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


来源:https://stackoverflow.com/questions/8360516/c-sharp-collection-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!