A. 玩具类
class Toy
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private ToyAddon addOn;
public ToyAddon AddOn
{
get { return addOn; }
set { addOn = value; }
}
public void RemoveAddons()
{
/*
* someone said: this could lead to possible memory leak
* if this class implements IDisposable,
* then we are not disposing any of the resource
* */
//this.addOn = null;
/* instead use this */
var disposableToyAddOn = this.addOn as IDisposable;
if (disposableToyAddOn != null)
disposableToyAddOn.Dispose();
this.addOn = null;
}
public override string ToString()
{
return String.Format("{0}, {1}",
this.name,
(this.AddOn == null) ? "" : addOn.AddOnName);
}
}
B. Toy Addon
class ToyAddon
{
private string addOnName;
public string AddOnName
{
get { return addOnName; }
set { addOnName = value; }
}
}
C. 主程序
class Program
{
static void Main(string[] args)
{
ToyAddon tAdd = new ToyAddon();
tAdd.AddOnName = "Amazing AddOn";
Toy t = new Toy();
t.Name = "Amazing Toy";
t.AddOn = tAdd;
t.RemoveAddons();
Console.WriteLine(t.ToString());
}
}
现在有人建议我检查一个拥有“having-a”对象是否实现了IDisposable接口,如果实现了则调用其dispose方法。 (请检查Toy类中的注释)
个人认为,如果我将引用设置为null,则位于堆上的对象将被GC标记为待回收。
如果该类(如ToyAddOn)实现IDisposable接口与否,在堆和栈上发生了什么以及GC的作用,如果能对此进行解释,那将不胜感激。