自定义克隆方法隐藏继承成员?

时间:2013-11-01 12:47:09

标签: c#

public interface IMyInterface : ICloneable
{
    IMyInterface Clone();
}
  

'TestApp.IMyInterface.Clone()'隐藏继承的成员   'System.ICloneable.Clone()'。如果隐藏了,请使用new关键字   意图。

我需要我的界面与ICloneable兼容。我该如何解决这种歧义?

更新

考虑这个具体的类,实现IMyInterface。我们的想法是它应该有一个有效的Clone方法实现ICloneable,这样任何接受ICloneable的方法都可以使用!

public class MyClass : IMyInterface
{
    #region ICloneable interface
    object ICloneable.Clone()
    {
        return this.Clone();
    }
    #endregion

    public IMyInterface Clone()
    {
        return new MyClass();
    }
}

现在,这个编译,但是有这个警告。如何摆脱警告保持与ICloneable界面的兼容性?

3 个答案:

答案 0 :(得分:3)

您收到该警告是因为ICloneable指定了Clone方法,该方法返回object;不是IMyInterface。您的Clone方法具有不同的签名,因此会隐藏ICloneable接口指定的签名。你可以放下它:

public interface IMyInterface : ICloneable
{
}

如果您需要两者,请使用new关键字:

public interface IMyInterface : ICloneable
{
    new IMyInterface Clone();
}

让您的实现看起来像这样:

public class MyInterface : IMyInterface
{
    object ICloneable.Clone() // explicit interface implementation
    {
        return this.Clone(); // calls the other Clone method
    }

    public IMyInterface Clone()
    {
        return new MyInterface
        {
            // member initializations
        };
    }
}

这将满足两个接口,而不是每个Clone实现中的重复代码。

用法:

IMyInterface i = new MyInterface();
MyInterface c = new MyInterface();

object x = i.Clone(); // Calling Clone on i calls the ICloneable.Clone implementation
IMyInterface y = c.Clone(); // Calling Clone on c calls the IMyInterface.Clone implementation

答案 1 :(得分:1)

此编译器警告告诉您代码令人困惑;阅读它的人可能不确定您是否试图覆盖基础成员或创建新成员。

您应该添加new关键字,以澄清您正在创建新成员。

请注意,实现您的界面的类需要实现两个 Clone()方法;其中至少有一个需要明确实施。

答案 2 :(得分:1)

您的方法与Clone()的IClonable接口规范同名。您应该考虑使您的IMyInterface更明确地指定克隆所执行的操作。示例:DeepCopy()/ ShallowCopy()。 或者您可以使用:

简单地替换基本Clone()
   public void new Clone()