简体   繁体   English

C#:抽象类需要实现接口吗?

[英]C#: Abstract classes need to implement interfaces?

My test code in C#: 我在C#中的测试代码:

namespace DSnA
{
    public abstract class Test : IComparable
    {

    }
}

Results in the following compiler error: 导致以下编译器错误:

error CS0535: 'DSnA.Test' does not implement interface member
'System.IComparable.CompareTo(object)'

Since the class Test is an abstract class , why does the compiler require it to implement the interface? 由于类Test是一个抽象类 ,为什么编译器要求它实现接口? Shouldn't this requirement only be compulsory for concrete classes? 这个要求不应该仅仅是具体课程的必修课吗?

In C#, a class that implements an interface is required to define all members of that interface. 在C#, 需要实现一个接口的类定义接口的所有成员。 In the case of an abstract class, you simply define those members with the abstract keyword: 在抽象类的情况下,您只需使用abstract关键字定义这些成员:

interface IFoo
{
    void Bar();
}

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

Or to put it another way: you don't have to "implement" it (which would be a terrible limitation on abstract classes); 或者换句话说:你不必 “实现”它(这对抽象类来说是一个可怕的限制); however, in C#, you do have to tell the compiler that you are deliberately passing the buck to concrete subclasses - and the above line of code shows how to do so. 但是,在C#中,您必须告诉编译器您是故意将降级传递给具体的子类 - 上面的代码行显示了如何执行此操作。

The comments and downvotes complaining that this is not an answer to the question are missing the point. 评论和支持者抱怨说这不是问题的答案,但却忽视了这一点。 Someone coming to Stack Overflow, having received this compiler error, but having an abstract class in which it would be a mistake to supply an implementation, are stuck without a good solution - would have to write implementation methods that threw runtime exceptions, a horrendous work-around - until they have the above information. 有人来到Stack Overflow,收到了这个编译错误,但是有一个抽象类,其中提供一个实现是一个错误,没有一个好的解决方案 - 将不得不编写引发运行时异常的实现方法,一个可怕的工作 - 在他们拥有上述信息之前。 Whether it is good or bad that C# requires this explicitness is outside the scope of Stack Overflow, and not relevant to the question nor this answer. C#需要这种显式性是好还是坏都超出了Stack Overflow的范围,与问题和这个答案无关。

Unlike Java, in C#: "an abstract class must provide implementations of all members of the interfaces that are listed in the base class list of the class. However, an abstract class is permitted to map interface methods onto abstract methods." 与Java不同,在C#中:“抽象类必须提供类的基类列表中列出的所有接口成员的实现。但是,允许抽象类将接口方法映射到抽象方法。”

https://msdn.microsoft.com/en-us/library/Aa664595(v=VS.71).aspx https://msdn.microsoft.com/en-us/library/Aa664595(v=VS.71).aspx

They don't have to actually implement the interface . 他们不必实际实现接口
The interface methods/properties can be abstract or even virtual as well. 接口方法/属性也可以是抽象的,甚至也可以是虚拟的。 So its up to the subclasses to actually implement them. 所以它由子类来实际实现它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM