垃圾收集、.NET、C#
我有三个对象 A、B 和 C。C 是 A 和 B 的子对象。C 引用了 A 和 B。A 和 B 引用了 C。 据我所知,当A和B对C的引用都被删除时,C就变成垃圾并被GC收集。
- 我的理解正确吗?
- 我应该将 C 中对 A 和 B 的引用设置为 NULL 吗?
- 如果是,有什么好处?
public class A { public C Cr { get; set; } }
public class B { public C Cr { get; set; } }
public class C
{
public A Ar { get; set; }
public B Br { get; set; }
}
class Program
{
static void Main(string[] args)
{
var oa = new A();
var ob = new B();
var oc = new C();
oc.Ar = oa;
oc.Br = ob;
oa.Cr = oc;
ob.Cr = oc;
// Some operation
oa.Cr = null;
ob.Cr = null;
//is the following code required?
// if yes, what is the benefit?
oc.Ar = null;
oc.Br = null;
}
谢谢拉姆
I have three objects A, B and C. C is the child of both A and B. C has reference to A and B. A and B has reference to C.
I understand that when the reference to C from both A and B gets deleted, C becomes garbage and will be collected by GC.
- Is my understanding correct?
- Should I set the Reference to A and B in C to NULL?
- If Yes, What is the benefit?
public class A { public C Cr { get; set; } }
public class B { public C Cr { get; set; } }
public class C
{
public A Ar { get; set; }
public B Br { get; set; }
}
class Program
{
static void Main(string[] args)
{
var oa = new A();
var ob = new B();
var oc = new C();
oc.Ar = oa;
oc.Br = ob;
oa.Cr = oc;
ob.Cr = oc;
// Some operation
oa.Cr = null;
ob.Cr = null;
//is the following code required?
// if yes, what is the benefit?
oc.Ar = null;
oc.Br = null;
}
Thanks
Ram
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果没有对 C 的实时引用,那么它就符合垃圾回收的条件。这并不意味着它将立即被垃圾收集。
如果某个对象即将符合垃圾回收条件,则无需在该对象内将引用设置为 null。
请注意,如果没有对 A、B 或 C 的“根”引用,它们将全部都有资格进行垃圾回收,即使它们继续相互引用。
If there are no live references to C, then it becomes eligible for garbage collection. That doesn't mean it will be garbage collected straight away.
There's no need for you to set references to null within an object if that object is about to become eligible for garbage collection.
Note that if there are no "root" references to A, B or C, they will all be eligible for garbage collection, even if they continue to have references to each other.