Explicit generic interface with class inheritance

2019-09-05 23:25发布

问题:

GENERIC INTERFACE:

interface ICloneable < T >  
{  
    T CopyFrom (T source);  
    T CopyFrom (T source);  
    T CopyTo (T destination);  
}

CLASS: Implements generic interface:

public class Entity: ICloneable < Entity >  
{  
    public int ID { get; set; }  
    public Entity CopyFrom (Entity source)  
    {  
    this.ID = source.ID;  
    return (this);  
    }  
}

WINDOWS FORM: This form should only accept T types that implement the above generic interface.

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();  
    }  
}

As you would guess, the call to ((ICloneable < T >) this.ObjectOriginal).CopyFrom(this.ObjectCurrent); is perfectly legal. However, the code above does not ensure that the type T passed in to the class implements ICloneable < T >. I have forced it through the constructor but that looks to be in bad taste.

The following two constructs are illegal and I wonder why:

class Computer < ICloneable < T >>: System.Windows.Forms.Form

OR

class Computer < T where T: ICloneable < T > >: System.Windows.Forms.Form

Any thoughts on how to achieve this?

回答1:

Instead of the first construct you could use

class Computer<T> : System.Windows.Forms.Form where T : ICloneable<T>   

Instead of the second one you could use

class Computer <T, TCloneable>: System.Windows.Forms.Form 
    where TCloneable : ICloneable<T>