.NET 中抽象类和接口有什么区别?
抽象类可以被另一个类继承,并要求人们重写抽象函数、抽象属性等。
接口也可以被另一个类实现,也要求人们实现函数、属性、索引器等
。我发现不同的是 Visual Studio 足够智能,可以自动生成此界面的必要成员。
那么,有什么不同呢?
谢谢你~
An abstract class can be inherited by another class, and require people to override the abstract functions, abstract properties, etc.
An interface also can be implemented by another class, also require people to implement the functions, properties, indexers, etc.
The only different I found is Visual Studio is smart enough to auto-generate the necessary members of this interface.
So, what's the different?
thanks you~
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
从概念上讲,我看到了一个简单的区别。
接口定义了对类的期望。它声明实现者必须提供某些行为(方法、属性、事件)。它没有规定一个类应该如何工作,而只是规定它应该做什么。
抽象类是无法自行实例化的基类。通常它提供一个部分实现,可以在派生自它的具体类之间共享。因此,它规定了类应该如何工作。
由于语言限制(例如,C# 不支持多重继承,接口除外),这又会导致一些实际差异。使用哪个实际上取决于您想要实现的目标。
Conceptually, I see a simple difference.
An interface defines expectations for a class. It declares that an implementor must provide certain behaviours (methods, properties, events). It doesn't prescribe how a class should work, merely what it should do.
An abstract class is a base class that cannot be instantiated on its own. Usually it provides a partial implementation that can be shared among concrete classes that derive from it. Thus it prescribes how a class should work.
This in turn leads to several practical differences because of language constraints (eg C# doesn't support multiple inheritance, except for interfaces). Which to use really depends on what you are trying to achieve.
在 .NET 中,类仅限于单一继承,但可以实现任意数量的接口。如果您从抽象类继承,那么这是您唯一可以使用的类。这可能不是什么大问题,但举例来说,它可能会阻止您从 MarshalByRefObject 继承。
此外,抽象类定义的行为仅限于从它继承的类。另一方面,由接口(IDisposable、IPrintable 等)定义的行为可以跨类层次结构应用。
In .NET, classes are limited to single inheritance but can implement any number of interfaces. If you inherit from an abstract class, that's the only one you can use. It may not be a big deal, but it would prevent you from perhaps inheriting from MarshalByRefObject down the road, as an example.
Also, the behavior defined by an abstract class is limited to the classes that inherit from it. On the other hand, behaviors defined by interfaces (IDisposable, IPrintable, etc.) can be applied across class hierarchies.
接口可以根本没有实现,但抽象类可以实现方法和属性。
An interface can have no implementation at all but an abstract class can implement methods and properties.
添加到@Jeremy简短而简洁的答案:)
抽象类将具有“abstract”和“virtual”关键字,用于指定方法或属性是否具有实现。
抽象方法/属性必须在具体类中实现,但虚拟方法/属性可能不会在具体类中被重写,因为它已经在抽象类中具有实现...
我希望我说清楚了:))
Adding to @Jeremy short and concise answer :)
An abstract class would have the "abstract" and "virtual" keywords that would specify if a method or a property have an implementation.
An abstract method/property would have to be implemented in the concrete class, but the virtual method/property may not be overridden in the concrete class since it already has an implementation in the abstract class...
I hope I made myself clear :))