C#集合继承 [英] c# collection inheritance

查看:110
本文介绍了C#集合继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有在C#中的集合,支持继承类似的概念,对象可以有出现包括所有从另一个要素,以及自己的?

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?

例如

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



所以,如果我如加2元的狗和1动物,然后又看了看有多少元素动物有我会看到3。

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.

我也可以把引用上述每3个元素,给动物3个元素和狗2我仍然有两个独立的,重叠的列出了哪些是可取的,但添加和删除元素可能成为棘手,在具有从两个集合中添加和删除狗的情况下添加或删除这个简单的例子。

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

您可以只保留了一组动物和使用LINQ来过滤它飞:

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

这篇关于C#集合继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆