在C#为什么同时存在于抽象类和接口? [英] Why do both the abstract class and interface exist in C#?

查看:303
本文介绍了在C#为什么同时存在于抽象类和接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么都存在在C#中抽象类和接口,如果我们可以通过使所有成员在类的抽象实现界面功能。

Why do both the abstract class and interface exist in C# if we can achieve the interface feature by making all the members in the class as abstract.

难道是因为:

  1. 接口存在有多重继承
  2. 这是有道理的有界面,因为对象的CAN-DO功能应该被放置在一个接口,而抽象基类。

请澄清

推荐答案

那么,一个抽象类,可以指定的部分的实现,但通常不是全部。 (说到这,这是完全可以提供一个抽象类,没有抽象成员,但很多虚拟的它与无操作实现)。接口提供的没有的实施,仅仅是一个合同。

Well, an abstract class can specify some implemetation, but usually not all of it. (Having said which, it's perfectly possible to provide an abstract class with no abstract members, but plenty of virtual ones which with "no-op" implementations). An interface provides no implementation, merely a contract.

您当然可以争辩说,如果允许多重继承的类,接口将在很大程度上没有意义的。

You could certainly argue that if multiple inheritance of classes were permitted, interfaces would be largely pointless.

我个人不急于选择整个是一个VS可以做的区别继承。它从来没有给我一个好该怎么做的只是在摆弄不同的想法,看哪些感受最灵活的直觉。 (再说,我是一个很有青睐组成了继承的家伙......)

Personally I don't get hung up on the whole "is-a" vs "can-do" distinction for inheritance. It never gives me as good an intuition about what to do as just playing around with different ideas and seeing which ones feel the most flexible. (Then again, I'm very much a "favour composition over inheritance" guy...)

编辑:正如反驳他的意见lbushkin的第三点是最方便的方法......你可以覆盖一个抽象方法与非虚拟的(在不能够进一步修改它的条款)通过密封吧:

Just as the most convenient way of rebutting lbushkin's third point in his comment... you can override an abstract method with a non-virtual one (in terms of not being able to override it further) by sealing it:

public abstract class AbstractBase
{
    public abstract void Foo();
}

public class Derived : AbstractBase
{
    public sealed override void Foo() {}
}

从类派生派生不能覆盖进一步。

我没有以任何方式暗示我要多重继承的实现 - 但如果我们的没有的拥有它(连同其复杂性),那么一个抽象类,它的只是的包含的抽象方法将完成的几乎的一切接口一样。 (有明确的接口实现的事情,但是这就是我能想到的此刻。)

I'm not in any way suggesting I want multiple inheritance of implementation - but if we did have it (along with its complexity) then an abstract class which just contained abstract methods would accomplish almost everything that an interface does. (There's the matter of explicit interface implementation, but that's all I can think of at the moment.)

这篇关于在C#为什么同时存在于抽象类和接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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