这行代码:
SettingsInstance = SomeOtherSettingsInstance;
不会复制任何物体内部,而是覆盖存储在SettingsInstance与存储在SomeOtherSettingsInstance参考参考。
对象本身并不聪明。
基本上,你已经执行的第一个最后3行后,你有这样的场景:
SomeOtherSettingsInstance -----> Object 1 in memory of type Settings
SettingsInstance --------------> Object 2 in memory of type Settings
^
|
+- References
你执行第三行之后,这是它的外观:
SomeOtherSettingsInstance --+--> Object 1 in memory of type Settings
/
SettingsInstance ---------+ Object 2 in memory of type Settings
现在你有两个对第一个对象的引用,一个通过每个变量,并且你已经留下刚刚创建的新对象以便垃圾收集器稍后再来拾取它。
如果你想复制内部,那么是的,你必须一次复制一个属性。
我定期创建克隆这样的支持:
public Settings Clone()
{
Settings clone = CreateCloneInstance();
CloneTo(clone);
return clone;
}
protected virtual Settings CreateCloneInstance()
{
return new Settings();
}
public virtual void CloneTo(Settings clone)
{
clone.RootFolder = RootFolder;
... + any other properties you might have
}
在你的情况下,你想复制以前的事情挂钩的事件,所以你会这样称呼它:
public Settings SettingsInstance = new Settings();
SettingsInstance.SettingsChanged += SettingsInstance_SettingsChanged;
SomeOtherSettingsInstance.CloneTo(SettingsInstance);
的我实现克隆支持的原因是由于对象层次结构。如果这不是你的问题(你不打算从设置继承),你可以这样做:
public Settings Clone()
{
Settings clone = new Settings();
CloneTo(clone);
return clone;
}
public void CloneTo(Settings clone)
{
clone.RootFolder = RootFolder;
... + any other properties you might have
}
由于事件处理程序设置克隆发生之前,事件将触发每次设置属性。 – smaclell 2010-02-20 20:57:59
好的谢谢,我将不得不一次做一个属性 – Dave 2010-02-20 20:58:40