如何保持对象的弱引用?
(仅供参考:这个问题是半理论性的。这不是我明确计划做的事情。)
我希望能够保留对我创建的所有对象的引用。也许是这样的:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 WeakReference - 它完全按照预期执行。使用它时要小心 - 每次取消引用时都必须检查引用是否仍然有效。
教程。
警告:仅仅因为该对象尚未被垃圾回收,并不意味着有人没有对其调用
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.
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.有一个特殊的东西就是这样命名的 - WeakReference
There is special thing which is named exactly this way - WeakReference