垃圾收集、.NET、C#

发布于 2024-11-01 13:23:08 字数 832 浏览 1 评论 0原文

我有三个对象 A、B 和 C。C 是 A 和 B 的子对象。C 引用了 A 和 B。A 和 B 引用了 C。 据我所知,当A和B对C的引用都被删除时,C就变成垃圾并被GC收集。

  1. 我的理解正确吗?
  2. 我应该将 C 中对 A 和 B 的引用设置为 NULL 吗?
  3. 如果是,有什么好处?

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.

  1. Is my understanding correct?
  2. Should I set the Reference to A and B in C to NULL?
  3. 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 技术交流群。

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

发布评论

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

评论(1

野生奥特曼 2024-11-08 13:23:08

如果没有对 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.

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