C# 我们必须使用接口的真实例子......不是抽象类......写一些代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9408555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Real example where we have to use interface ... not abstract class... write some code
提问by Pankaj Sharma
In my interview i was aked that give some realtime scenario where you can implement interface.. write some code also.
They want to ask we have abstract methods then why do we need interface... write some code.
在我的采访中,我被要求提供一些实时场景,您可以在其中实现接口......也编写一些代码。
他们想问我们有抽象方法那么为什么我们需要接口......写一些代码。
Thanks in Advance
提前致谢
采纳答案by Chuck Norris
As MSDNshows
正如MSDN所示
- If you anticipate creating multiple versions of your component,create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
- If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
- If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
- If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
- 如果您希望创建组件的多个版本,请创建一个抽象类。抽象类提供了一种简单易行的方式来对组件进行版本控制。通过更新基类,所有继承类都会随着更改自动更新。另一方面,接口一旦创建就不能更改。如果需要新版本的接口,您必须创建一个全新的接口。
- 如果您正在创建的功能对广泛的不同对象有用,请使用接口。抽象类应该主要用于密切相关的对象,而接口最适合为不相关的类提供通用功能。
- 如果您正在设计小而简洁的功能,请使用接口。如果您正在设计大型功能单元,请使用抽象类。
- 如果要在组件的所有实现中提供通用的已实现功能,请使用抽象类。抽象类允许您部分实现您的类,而接口不包含任何成员的实现。
回答by Induster
Because you can implement as many interfaces as you want. with an abstract class you can only inherit from one.
因为您可以实现任意数量的接口。对于抽象类,您只能从一个继承。
回答by uday
Read this great documentation in MSDN:
在 MSDN 中阅读这个很棒的文档:
Recommendations for Abstract Classes vs. Interfaces
Abstract Class versus Interfacefrom Codeproject.com with sample code too.
来自 Codeproject.com 的抽象类与接口也带有示例代码。
Hope it helps!
希望能帮助到你!

