What is the difference between abstract class and interface in .NET?
An abstract class can开发者_如何学Python 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~
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.
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.
- You can provide partial implementation with an abstract class.
- Interfaces don't smash the inheritance line; abstract classes do. You might want to mandate behaviour/capabilities without creating an is-a relationship.
An interface can have no implementation at all but an abstract class can implement methods and properties.
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 :))
精彩评论