通用接口:
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 FORM:这个表单应该只接受实现上述通用接口的 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();
}
}
正如您所猜测的那样,调用 to((ICloneable < T >) this.ObjectOriginal).CopyFrom(this.ObjectCurrent);
是完全合法的。但是,上面的代码并不能确保传入类的类型 T 实现了ICloneable < T >
. 我已经通过构造函数强制它,但这看起来很糟糕。
以下两个构造是非法的,我想知道为什么:
class Computer < ICloneable < T >>: System.Windows.Forms.Form
或者
class Computer < T where T: ICloneable < T > >: System.Windows.Forms.Form
关于如何实现这一目标的任何想法?