亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

對象的屬性是用 C# 中的對象進行垃圾回收,還是它們有單獨的 gc 機制

對象的屬性是用 C# 中的對象進行垃圾回收,還是它們有單獨的 gc 機制

C#
慕容708150 2022-12-31 11:09:50
我只是在想一個問題,如果有這樣的課程:public class A {    public CustomType PropertyA { get; set; }    public CustomType PropertyB { get; set; }}我創建了它的一個實例:var a = new A {    PropertyA = SomeValue,    PropertyB = SomeOtherValue};然后我設置PropertyA為 null 就像a.PropertyA = null;將PropertyA的值作為垃圾收集一樣,還是在對象被收集之前不會被a收集?
查看完整描述

1 回答

?
絕地無雙

TA貢獻1946條經驗 獲得超4個贊

通過這個例子,我們可以說 GC 對對象的任何屬性實例都是獨立工作的。


using System;


public class Dog

{

    public Dog(string name)

    {

        this.Name = name;

    }

    public string Name;

    public Breed Breed;

}


public class Breed

{

    public Breed(string name)

    {

        Name = name;

    }

    public string Name;

}


public class Program

{

    public static void Main()

    {

        Dog dog = new Dog("Bowser");

        dog.Breed = new Breed("Pug");

        WeakReference dogRef = new WeakReference(dog);

        WeakReference breedRef = new WeakReference(dog.Breed);

        Console.WriteLine(dogRef.IsAlive);

        Console.WriteLine(breedRef.IsAlive);


        dog.Breed = null;

        GC.Collect();

        Console.WriteLine(breedRef.IsAlive);


        dog = null;

        GC.Collect();

        Console.WriteLine(dogRef.IsAlive);

    }

}

輸出:

true

true

false

false


查看完整回答
反對 回復 2022-12-31
  • 1 回答
  • 0 關注
  • 99 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號