C#:抽象类需要实现接口吗? [英] C#: Abstract classes need to implement interfaces?

查看:27
本文介绍了C#:抽象类需要实现接口吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C# 中的测试代码:

My test code in C#:

namespace DSnA
{
    public abstract class Test : IComparable
    {

    }
}

导致以下编译器错误:

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

既然Test类是一个抽象类,为什么编译器需要它来实现接口?这个要求不应该只是对具体类强制性吗?

Since the class Test is an abstract class, why does the compiler require it to implement the interface? Shouldn't this requirement only be compulsory for concrete classes?

推荐答案

在 C# 中,实现接口的类需要来定义该接口的所有成员.对于抽象类,您只需使用 abstract 关键字定义这些成员:

In C#, a class that implements an interface is required to define all members of that interface. In the case of an abstract class, you simply define those members with the abstract keyword:

interface IFoo
{
    void Bar();
}

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

或者换句话说:你不必实现"它(这对抽象类来说是一个可怕的限制);然而,在 C# 中,您确实必须告诉编译器您是故意将责任推给具体的子类 - 上面的代码行显示了如何这样做.

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.

抱怨这不是问题的答案的评论和反对票没有抓住要点.有人来到 Stack Overflow,收到这个编译器错误,但有一个抽象类,在其中提供实现是错误的,没有一个好的解决方案被卡住 - 必须编写抛出运行时异常的实现方法,这是一项可怕的工作-around - 直到他们获得上述信息.C# 要求这种明确性是好是坏都超出了 Stack Overflow 的范围,与问题和答案无关.

这篇关于C#:抽象类需要实现接口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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