具有类继承的显式通用接口

时间:2012-01-07 17:41:12

标签: c# generics inheritance interface explicit

GENERIC INTERFACE

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

有关如何实现这一目标的任何想法?

1 个答案:

答案 0 :(得分:3)

您可以使用

代替第一个构造
class Computer<T> : System.Windows.Forms.Form where T : ICloneable<T>   

而不是第二个,你可以使用

class Computer <T, TCloneable>: System.Windows.Forms.Form 
    where TCloneable : ICloneable<T>    
相关问题