c# - 在基类中定义后,是否需要在派生类中定义相同的接口(interface)?

标签 c# interface

<分区>

例如,我有一个这样的基类:

class Base: ICloneable
{
    public object Clone()
    {
      //something
    }
}

这些 Derived 类之间有什么区别吗?

class Derived: Base, ICloneable
{
    //something
}
class Derived: Base
{
    //something
}

最佳答案

好吧,你可能需要这样做;这是一种可能的情况:

克隆时,我们通常希望通过克隆对象类型返回非通用对象:

class Base {
  // We can't declare this method as virtual: Derived class will return Derived 
  public Base Clone() {
    ...
  }
}

...

Base test = new Base();

Base duplicate = test.Clone(); 

如果我们想要实现IClonable,我们必须显式(为了解决Clone()名称冲突):

class Base : ICloneable {
  public Base Clone() {
    ... 
  }

  // This method is efficiently private, and that's why can't be virtual
  object ICloneable.Clone() => Clone();
}

现在我们想要一个也可以被克隆的 Derived 类:

class Derived : Base {
  // Note that now we have new Clone method which returns Derived instance (not Base one)
  public new Derived Clone() {
    ...
  }
}

...

Derived test = new Derived();

Derived duplicate = test.Clone();

如果我们保持这样,那么我们将有错误的行为:

 Derived test = new Derived();

 // This will be wrong: 
 // Base.ICloneable.Clone() will be called which executes "Base Clone()" method
 // instead of expected "new Derived Clone()"
 object clone = (test as IClonable).Clone();

所以我们必须重新实现IClonable接口(interface):

class Derived : Base, ICloneable {
  // Please, note that now we have new Clone method which returns Derived instance
  public new Derived Clone() {
    ...
  }

  // This ICloneable implementation will call Derived Clone()
  object ICloneable.Clone() => Clone();
}

...

// Derived ICloneable.Clone() will be called
// which executes "new Derived Clone()" method
object clone = (test as IClonable).Clone();

关于c# - 在基类中定义后,是否需要在派生类中定义相同的接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59072174/

相关文章:

go - 在 Golang 中传递 interface{} 或 []interface{}

C#:实现具有任何类型属性的接口(interface)

c# - 将 dotnet 核心 (.NET Core) 嵌入到 Windows/Linux 上的 native 应用程序中

c# - 在 FlUrl 中,我尝试使用 EnableCookies() 并抛出空引用异常

javascript - 在 ES6 之前的 Typescript 中实现 Iterator<T> 的推荐方法

constructor - 在 Kotlin 中匿名实现接口(interface)导致 "has no constructors"错误

c# - 你调用的对象是空的

c# - ORA-00932 : inconsistent datatypes: expected DATE got NUMBER

c# - 单元测试 Sitecore LicenseManager

java - 查找实现接口(interface)的 Java 类