如何在 C# 中迭代类的实例?
有没有办法在 C# 中迭代类的实例?这些实例不在集合中进行跟踪或管理。
Is there a way to iterate over instances of a class in C#? These instances are not tracked or managed in a collection.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不在常规框架内。您需要手动跟踪它们。
但是,您可以在 Windbg/sos 中执行此操作 - 主要用于调试目的(不适用于例程代码)。
Not inside the regular framework. You would need to track them manually.
You can, however, do this in windbg/sos - mainly for debugging purposes (not for routine code).
您必须在某个地方引用它们,或者至少知道在哪里查找,因此在识别它们时,您可能会将它们放入一个集合中,然后进行迭代。
如果您不知道引用位于哪里,那么您就必须引入某种跟踪机制。也许是类型的静态集合?但必须谨慎实施。
You have to have references to them somewhere, or at least know where to look, so in identifying them you'd probably put them into a collection which you'd then iterate.
If you don't know where the references live, then you'd have to have to introduce some kind of tracking mechanism. Perhaps a static collection on the type? It would have to be implemented carefully though.
不直接。
从概念上讲,您可以让对象将自身的副本放置到某个众所周知的位置(例如静态集合),然后使用它进行迭代,但是您必须确保在某个时刻从该集合中清除实例否则它永远不会被垃圾收集。
Not directly.
You could conceptually have your object place a copy of itself into some well-known place (e.g. a static collection) and then use that to iterate, but then you'd have to make sure you cleared the instance out of that collection at some point or else it'll never get garbage collected.
在评论线程
In the comment thread on this post there is an interesting discussion and solution related to this question.
正如马克所说,如果你想用代码来完成它,你需要保留它们的集合。如果您正在调试,请查看此博客文章: http ://blogs.msdn.com/tess/archive/2006/01/23/516139.aspx
如果您需要内存中某种类型的所有对象实例的集合,您可以考虑使用集合System.WeakRef 的弱引用是不保留其引用的对象的引用。这将使您可以保留要枚举的对象实例的弱引用集合。请查看帮助中的 Weakrefs 以获取更多信息。
As Marc said, if you want to do it in code, you would need to keep a collection of them. If you are debugging, have a look at this blog post: http://blogs.msdn.com/tess/archive/2006/01/23/516139.aspx
If you need a collection in memory of all of the object instances of a certain type, you could consider using a collection of System.WeakRef's A weak ref is a reference that does not keep the object that it references. This would let you keep a collection of weak-refs to the object instances you want to enumerate. Have a look at Weakrefs in the help for more info.