1 回答

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超4個贊
通過這個例子,我們可以說 GC 對對象的任何屬性實(shí)例都是獨(dú)立工作的。
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
- 1 回答
- 0 關(guān)注
- 95 瀏覽
添加回答
舉報