时间:2019-03-17 标签:c#collectioninheritance
C# 中是否有一个集合支持类似于继承的概念,即对象可以包含来自另一个对象以及它们自身的所有元素?
例如:
HashSet<animal> animals = new HashSet<animal>();
HashSet<dog> dogs = new HashSet<dog>();
animals.also_appears_to_include(dogs);
因此,如果我向狗添加 2 个元素,向动物添加 1 个元素,那么看看动物有多少个元素,我会看到 3。
或者,我可以在每个元素中引用上述 3 个元素,为动物提供 3 个元素, dogs 2. 我仍然有两个独立的、重叠的列表,这是可取的,但是添加和删除元素可能会变得很棘手,在这个简单的示例中,在添加和删除狗的情况下必须从两个集合中添加或删除元素。
或者我可以使用此功能实现我自己的集合。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
MS 没有提供任何可以实现您的功能的功能,但是
您可以只保留一组动物并使用 linq 动态过滤它:
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:
让狗和猫继承接口,并创建接口的 HashSet,而不是类。或者使用基类。
例如:
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:
那没那么棘手
Thats not that tricky