What is the difference between an interface with default implementation and abstract class? [duplicate]

坚强是说给别人听的谎言 提交于 2020-08-02 04:34:25

问题


C# 8.0 has introduced a new language feature – default implementations of interface members.

public interface IRobot
{
    void Talk(string message)
    {
        Debug.WriteLine(message);
    }
}

The new default interface implementations provides the elements of the traits language. However is is also blurring the line between what is an abstract class and what is an interface.

What is now the benefit of using an abstract class instead of an interface with default implemenation?


回答1:


Funny enough, but the CLR implements default interfaces as abstract classes. CLR supports multiple inheritance. Here is a good article about this.

In C#, you need default interfaces when you need to implement (in this case actually inherit from) multiple interfaces, because the language doesn't let you inherit from multiple classes.

An abstract class also allows you to have state. State, i.e. fields, are not allowed in interfaces.



来源:https://stackoverflow.com/questions/58116148/what-is-the-difference-between-an-interface-with-default-implementation-and-abst

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