当基类实现抽象时,在派生类上指定实现接口 [英] Specify implement interface on derived class when base class implements it abtract

查看:67
本文介绍了当基类实现抽象时,在派生类上指定实现接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否在派生类上实现接口(如果基本抽象类已经实现抽象接口的话)是否存在(运行时)差异?

I was wondering if there are any (runtime) difference if I implement an interface on a derived class if the base abstract class implements it already abstract:

public interface IFoo
{
  void Bar();
}

public abstract class Base : IFoo
{
  public abstract void Bar();
}

public class Derived : Base, IFoo // does this make any difference?
{
  public override void Bar()
  {
    // do something
  }
}

例如,当我检查实例是否在运行时实现接口等时,在Derived上写入实现" IFoo有什么区别吗?

Is there any difference writing the "implemention" IFoo on Derived for example when I check if an instance implements an interface at runtime etc.?

推荐答案

请考虑以下示例.必须做到以下几点?

Consider following on your example. Must the following be possible?

void f(Base b){
    IFoo ifoo = b;
} 

因为对象b是Base,所以它必须是IFoo,因为Base实现了IFoo.现在考虑以下内容.

Because an object b is a Base, it must be an IFoo because Base implements IFoo. Now consider the following.

var d = new Derived();
f(d);

由于d是派生对象,因此它是一个基类,因为派生对象继承自Base.因此,我们可以像以前一样将其传递给f,然后将其分配给IFoo.

Since d is a Derived, it is a Base, because derived inherits from Base. Because of this, we can pass it to f, where it is then assigned to an IFoo, as we did before.

本质上,由于派生类仍然也是其所有基类,因此它已经实现了其所有基类的接口.该语言的设计者承认这一点,因此无需重新声明派生类正在实现由其基类实现的接口.

Essentially, because a derived class still is also all of its base classes, it already implements all of its base classes' interfaces. The designers of the language acknowledged this and there is no need to redeclare that a derived class is implementing interfaces that are implemented by its base classes.

我想可能是由于您将方法主体实际放置在何处而引起您的问题,但这确实无关紧要.接口的声明是该类型对象的其他使用者的合同.那些使用者不在乎方法主体的定义位置,他们所关心的只是当他们拥有IFoo时,它具有签名为void Bar()的方法,可以调用它,正如我前面所展示的,继承必须包括所有接口,因此无需再次声明它们.

I guess that maybe your question arises because of where you actually put the method body, but that really isn't relevant. The declaration of the interface is a contract for other consumers of objects of that type. Those consumers don't care where the method body was defined, all that they care is that when they have an IFoo, that it has a method with the signature void Bar() that can be called, as I showed earlier, inheritance must include all interfaces, so there is no need to declare them again.

这篇关于当基类实现抽象时,在派生类上指定实现接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆