Specify implement interface on derived class when base class implements it abtract

…衆ロ難τιáo~ 提交于 2020-05-29 05:16:11

问题


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
  }
}

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


回答1:


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

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

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

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.

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.




回答2:


The answer is No. There is no difference.

The Class Derived inherits from Base and Base in turn inherits from IFoo.

So, there is no necessity for you to "Implement" both Base and IFoo when defining the class Derived.

The hierarchy is established when you are defining the class Base:

public abstract class Base : IFoo

and continued when you define Derived as below:

public abstract class Derived : Base


The only problem may arise when you "Remove" Base from the hierarchy by redefining the Base class by removing the : IFoo implementation from the Base class definition as below:

public abstract class Base


The bottom line is: , IFoo is redundant and is therefore not necessary.



来源:https://stackoverflow.com/questions/36568228/specify-implement-interface-on-derived-class-when-base-class-implements-it-abtra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!