本文介绍了具有类继承的显式通用接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通用接口:

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类型.

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

您可能会猜到,对((ICloneable < T >) this.ObjectOriginal).CopyFrom(this.ObjectCurrent);的调用是完全合法的.但是,上面的代码不能确保确保传入类的类型T实现ICloneable < T >.我已将其强制通过构造函数,但这看起来不好.

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?

推荐答案

您可以使用第一个构造代替

Instead of the first construct you could use

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

您可以使用第二个代替

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

这篇关于具有类继承的显式通用接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 20:15