ICloneable 定義單一方法 Clone(),但文件同時支援淺層複製與深層複製,未強制規範。這導致:
string):string 為不可變型別,淺層複製安全。其他參考型別若需深層複製,手動實作更清晰。結論:沒有任何理由給實值型別實作 ICloneable。
class BaseType : ICloneable {
public object Clone() {
var r = new BaseType(); // 僅複製基類部分!
r._label = _label;
Array.Copy(_values, r._values, _values.Length);
return r;
}
}
class Derived : BaseType { ... }
// Derived.Clone() 回傳 BaseType 實例,轉型失敗得 null
基類實作 ICloneable 強制所有衍生類別必須正確覆寫,否則行為錯誤。這對衍生類別是嚴苛契約。
protected BaseType(BaseType other) 複製建構函式。ICloneable 並呼叫基類複製建構函式。sealed)實作 ICloneable,終結繼承鏈複製義務。class BaseType {
protected BaseType(BaseType other) { ... } // 複製基類欄位
}
sealed class Derived : BaseType, ICloneable {
private Derived(Derived other) : base(other) { ... }
public object Clone() => new Derived(this);
}
ICloneable。ICloneable。盡量避免 ICloneable,讓類別設計更簡單、更安全。