时间:2019-03-17 标签:c#collectioninheritance

发布于 2024-12-19 09:28:08 字数 461 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我也只是我 2024-12-26 09:28:08

MS 没有提供任何可以实现您的功能的功能,但是

您可以只保留一组动物并使用 linq 动态过滤它:

var animals = new HashSet<Animal>();
var dogs = animals.OfType<Dog>();

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>();
柠檬色的秋千 2024-12-26 09:28:08

让狗和猫继承接口,并创建接口的 HashSet,而不是类。或者使用基类。

例如:

HashSet<IAnimal>

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>
懒猫 2024-12-26 09:28:08

那没那么棘手

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

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

Thats not that tricky

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

//Removing 
Dogs.Remove( animal );
Animals.Remove( animal );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文