简体   繁体   English

从子对象中找到“集合”

[英]Find “Collection” from subobject

Is there a method to understand if a generic C# Object is part of a collection? 有没有一种方法可以了解通用C#对象是否是集合的一部分? And is there a way to retrieve said collection? 有没有办法检索所述收藏?

I know an Object is not aware of being part of another (no references stored anywhere about parents) but maybe one could use reflection on generic collections. 我知道一个对象并没有意识到自己是另一个对象的一部分(没有引用存储在父母的任何地方),但是也许一个对象可以对通用集合使用反射。

To answer original question : no, you're not supposed to be able to find parent collection of an object, and reflection probably won't help. 要回答原始问题:不,您不应该能够找到对象的父级集合,并且反射可能无济于事。

But you may be able to achieve what you need by modifying behavior of ICollection.Add() by using extension methods and storing in each added objects a reference to their common container. 但是您可以通过使用扩展方法修改ICollection.Add()的行为并在每个添加的对象中存储对其公共容器的引用来实现所需的功能。

Putting additional data in objects seems to be achievable, as it is stated here : How can additional data be associated with existing objects using extension methods? 如此处所述,将附加数据放入对象似乎是可以实现的: 如何使用扩展方法将附加数据与现有对象关联?

There may be other solutions to achieve what you need, but on my self I'd go with something like that. 可能还有其他解决方案可以满足您的需求,但就我个人而言,我会选择类似的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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