如何在 C# 中迭代​​类的实例?

发布于 2024-08-12 01:46:21 字数 44 浏览 6 评论 0原文

有没有办法在 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 技术交流群。

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

发布评论

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

评论(5

柳若烟 2024-08-19 01:46:21

不在常规框架内。您需要手动跟踪它们。

但是,您可以在 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).

千仐 2024-08-19 01:46:21

您必须在某个地方引用它们,或者至少知道在哪里查找,因此在识别它们时,您可能会将它们放入一个集合中,然后进行迭代。

如果您不知道引用位于哪里,那么您就必须引入某种跟踪机制。也许是类型的静态集合?但必须谨慎实施。

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.

陌生 2024-08-19 01:46:21

不直接。

从概念上讲,您可以让对象将自身的副本放置到某个众所周知的位置(例如静态集合),然后使用它进行迭代,但是您必须确保在某个时刻从该集合中清除实例否则它永远不会被垃圾收集。

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.

森末i 2024-08-19 01:46:21

在评论线程

In the comment thread on this post there is an interesting discussion and solution related to this question.

日久见人心 2024-08-19 01:46:21

正如马克所说,如果你想用代码来完成它,你需要保留它们的集合。如果您正在调试,请查看此博客文章: 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.

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