如何保持对象的弱引用?

发布于 2024-12-09 09:32:57 字数 353 浏览 0 评论 0原文

(仅供参考:这个问题是半理论性的。这不是我明确计划做的事情。)

我希望能够保留对我创建的所有对象的引用。也许是这样的:

class Foo
{
    private static List<Foo> AllMyFoos = new List<Foo>();

    public Foo()
    {
        AllMyFoos.Add(this);
    }
}

问题是现在我的 Foo 都不会失去焦点并被垃圾收集。有没有什么方法可以在不妨碍垃圾收集器的情况下保留引用?

理想情况下,我只是列出仍在使用的 Foos,而不是所有曾经使用过的 Foos。

(FYI: This question is half thoretical. It is not something which I am definatly planning on doing.)

I would like to be able to keep a reference to all the objects that I create. Maybe like this:

class Foo
{
    private static List<Foo> AllMyFoos = new List<Foo>();

    public Foo()
    {
        AllMyFoos.Add(this);
    }
}

The trouble with this is that now none of my Foos can ever drop out of focus and be garbage collected. Is there any way of keeping a referance without getting in the way of the garbage collector?

Ideally I just of a list of Foos that are still being used, not all Foos which have ever been used.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

枫林﹌晚霞¤ 2024-12-16 09:32:57

使用 WeakReference - 它完全按照预期执行。使用它时要小心 - 每次取消引用时都必须检查引用是否仍然有效

教程


Foo foo = AllMyFoos[index].Target as Foo;
if (foo == null)
{
   // Object was reclaimed, so we can't use it.
}
else
{
   // foo is valid. My theoretical curiosity can be satisfied
}

警告:仅仅因为该对象尚未被垃圾回收,并不意味着有人没有对其调用Dispose,或者以其他方式将其置于某种状态不准备再次使用。

Use WeakReference - it does exactly what it is supposed to. Be careful while working with it - you have to check if the reference is still valid every time you dereference it.

Tutorial.


Foo foo = AllMyFoos[index].Target as Foo;
if (foo == null)
{
   // Object was reclaimed, so we can't use it.
}
else
{
   // foo is valid. My theoretical curiosity can be satisfied
}

Warning: Just because the object hasn't yet been garbage collected doesn't mean someone hasn't called Dispose on it, or in some other way put it into a state that it is not prepared to be used again.

笑看君怀她人 2024-12-16 09:32:57

有一个特殊的东西就是这样命名的 - WeakReference

There is special thing which is named exactly this way - WeakReference

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