通用接口:明確的通用接口
interface ICloneable <T>
{
T CopyFrom (T source);
T CopyFrom (T source);
T CopyTo (T destination);
}
CLASS:實現通用接口:
public class Entity: ICloneable <Entity>
{
public int ID { get; set; }
public Entity CopyFrom (Entity source)
{
this.ID = source.ID;
return (this);
}
}
Windows窗體:本表只接受實現T型性格上面的通用接口。
public sealed partial class Computer <T>: System.Windows.Forms.Form
{
private T ObjectCurrent { get; set; }
private T ObjectOriginal { get; set; }
public Computer (HouseOfSynergy.Library.Interfaces.ICloneable <T> @object)
{
this.ObjectOriginal = (T) @object;
this.ObjectCurrent = @object.Clone();
}
private void buttonOk_Click (object sender, System.EventArgs e)
{
((ICloneable <T>) this.ObjectOriginal).CopyFrom(this.ObjectCurrent);
this.Close();
}
}
正如您所猜測的,致電((ICloneable <T>) this.ObjectOriginal).CopyFrom(this.ObjectCurrent);
是完全合法的。但是,上面的代碼不保證確保傳遞給類的T實現了ICloneable <T>
。我強迫它通過構造函數,但看起來很糟糕。
以下兩種結構是非法的,我不知道爲什麼:
class Computer < ICloneable <T>>: System.Windows.Forms.Form
OR
class Computer < T where T: ICloneable <T> >: System.Windows.Forms.Form
任何思考如何實現這一目標?
你說的是Java或C#? – 2012-01-07 18:54:27
爲什麼java標籤?這顯然是C#代碼。 – GolfWolf 2012-01-08 14:25:01
對不起,這是一個錯字。修復。 – 2012-01-08 14:35:05