具有类继承的显式泛型接口
本文关键字:泛型接口 继承 | 更新日期: 2023-09-27 18:19:46
通用接口:
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();
}
}
正如您所猜测的,对((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
对如何实现这一目标有什么想法吗?
您可以使用而不是第一个构造
class Computer<T> : System.Windows.Forms.Form where T : ICloneable<T>
你可以用代替第二个
class Computer <T, TCloneable>: System.Windows.Forms.Form
where TCloneable : ICloneable<T>