C# 接口和类有什么区别,为什么我可以在类中直接实现方法时使用接口?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10914802/
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
What is the difference between an interface and a class, and why I should use an interface when I can implement the methods directly in the class?
提问by Learner
I am aware that this is a very basic question, but an interviewer asked me in a very trick way and I was helpless :(
我知道这是一个非常基本的问题,但是面试官问了我很狡猾的方式,我很无助:(
I know only material or theoretical definition for an interface and also implemented it in many projects I worked on. But I really don't understand why and how is this useful.
我只知道接口的材料或理论定义,并且还在我参与的许多项目中实现了它。但我真的不明白这为什么以及如何有用。
I also don't understand one thing in interface. i.e for example, we use
我也不明白界面中的一件事。即例如,我们使用
conn.Dispose();in finally block. But I don't see that class is implementing or inheriting IDisposableinterface (SqlConnection) class I mean. I am wondering how I can just call the method name. Also in the same thing, I am not understanding how Dispose method works as because, we need to implement the function body with our own implementation for all interface methods. So how Interfaces are accepted or named as contracts? These questions kept on rolling in my mind till now and frankly I never saw any good thread that would explain my questions in a way that I can understand.
conn.Dispose();在 finally 块中。但我没有看到该类正在实现或继承IDisposable接口 ( SqlConnection) 类,我的意思是。我想知道如何只调用方法名称。同样在同一件事上,我不理解 Dispose 方法是如何工作的,因为我们需要使用我们自己的所有接口方法实现来实现函数体。那么接口是如何被接受或命名为契约的呢?直到现在,这些问题一直在我的脑海中盘旋,坦率地说,我从未见过任何能以我能理解的方式解释我的问题的好线索。
MSDN as usual looks very scary and no single line is clear there (Folks, kindly excuse who are into high level development, I strongly feel that any code or article should reach the mind of anyone who see it, hence like many others say, MSDN is not of use).
像往常一样 MSDN 看起来很可怕,那里没有一行是清楚的(伙计们,请原谅那些从事高级开发的人,我强烈认为任何代码或文章都应该到达任何看到它的人的脑海中,因此就像许多其他人所说的,MSDN没有用)。
The interviewer said:
面试官说:
He has 5 methods and he is happy to implement it in the class directly, but if you have to go for Abstract class or interface, which one you choose and why ? I did answered him all the stuffs that I read in various blog saying advantage and disadvantage of both abstract class and interface, but he is not convinced, he is trying to understand "Why Interface" in general. "Why abstract class" in general even if I can implement the same methods only one time and not gona change it.
他有 5 个方法,他很乐意直接在类中实现它,但是如果您必须使用抽象类或接口,您选择哪一个,为什么?我确实回答了他在各种博客中读到的所有内容,说抽象类和接口的优缺点,但他不相信,他试图从总体上理解“为什么是接口”。“为什么是抽象类”,即使我只能实现一次相同的方法并且不会改变它。
I see no where in net, I could get an article that would explain me clearly about interfaces and its functioning. I am one of those many programmers, who still dont know about interfaces (I know theoretical and methods I used) but not satisfied that I understood it clearly.
我在网络上看不到任何地方,我可以得到一篇文章,可以清楚地解释接口及其功能。我是众多程序员中的一员,他们仍然不了解接口(我知道我使用的理论和方法)但不满足于我清楚地理解它。
采纳答案by Guilherme de Jesus Santos
Interfaces are excellent when you want to create something like it:
当您想创建类似的东西时,接口非常好:
using System;
namespace MyInterfaceExample
{
public interface IMyLogInterface
{
//I want to have a specific method that I'll use in MyLogClass
void WriteLog();
}
public class MyClass : IMyLogInterface
{
public void WriteLog()
{
Console.Write("MyClass was Logged");
}
}
public class MyOtherClass : IMyLogInterface
{
public void WriteLog()
{
Console.Write("MyOtherClass was Logged");
Console.Write("And I Logged it different, than MyClass");
}
}
public class MyLogClass
{
//I created a WriteLog method where I can pass as a parameter any object that implements IMyLogInterface.
public static void WriteLog(IMyLogInterface myLogObject)
{
myLogObject.WriteLog(); //So I can use WriteLog here.
}
}
public class MyMainClass
{
public void DoSomething()
{
MyClass aClass = new MyClass();
MyOtherClass otherClass = new MyOtherClass();
MyLogClass.WriteLog(aClass);//MyClass can log, and have his own implementation
MyLogClass.WriteLog(otherClass); //As MyOtherClass also have his own implementation on how to log.
}
}
}
In my example, I could be a developer who writes MyLogClass, and the other developers, could create their classes, and when they wanted to log, they implement the interface IMyLogInterface. It is as they were asking me what they need to implement to use WriteLog()method in MyLogClass. The answer they will find in the interface.
在我的示例中,我可以是编写 的开发人员MyLogClass,而其他开发人员可以创建他们的类,当他们想要记录时,他们实现接口IMyLogInterface。就像他们问我他们需要实现什么才能WriteLog()在MyLogClass. 他们会在界面中找到答案。
回答by poy
Interfaces allow the class designer to make the available methods very clear for the end user. They are also an integral part of polymorphism.
接口允许类设计者为最终用户提供非常清晰的可用方法。它们也是多态性的组成部分。
回答by Erix
C# doesn't have duck typing - just because you know a certain method is implemented across a set of concrete classes doesn't mean you can treat them all the same with regards to calling that method. Implementing an interface allows you to treat all classes implementing it as the same type of thing, with regards to what that interface defines.
C# 没有鸭子类型 - 仅仅因为您知道某个方法是跨一组具体类实现的,并不意味着您可以在调用该方法时对它们一视同仁。实现接口允许您将实现它的所有类视为相同类型的事物,这与该接口定义的内容有关。
回答by Massimiliano Peluso
I won't post the definition of an interface against an abstract class because I think you know very well the theory and I assume you know the SOLID principles so let's get practical.
我不会针对抽象类发布接口的定义,因为我认为您非常了解理论,并且我假设您了解 SOLID 原则,所以让我们开始实践。
As you know interfaces cannot have any code so the dis-vantage are quite simple to understand.
如您所知,接口不能有任何代码,因此缺点很容易理解。
if you need to initialize the property of your class providing a constructor or you want to provide part of the implementation an abstract class would be a good fit against an interface which would not allow you to do that.
如果您需要初始化提供构造函数的类的属性,或者您想提供实现的一部分,则抽象类将非常适合不允许您这样做的接口。
So in very general you should prefer abstract class to interfaces when you need to provide a constructor or any code to the client which will inherit/extend your class
因此,一般而言,当您需要向将继承/扩展您的类的客户端提供构造函数或任何代码时,您应该更喜欢抽象类而不是接口
回答by Jeow Li Huan
You can only inherit from one abstract class. You can inherit from multiple interfaces. This determines what I use for most of the cases.
您只能从一个抽象类继承。您可以从多个接口继承。这决定了我在大多数情况下使用什么。
The advantage of abstract class would be that you can have a base implementation. However, in the case of IDisposable, a default implementation is useless, since the base class does not know how to properly clean things up. Thus, an interface would be more suitable.
抽象类的优点是您可以拥有基本实现。然而,在 IDisposable 的情况下,默认实现是无用的,因为基类不知道如何正确清理。因此,接口会更合适。
回答by SliverNinja - MSFT
Interfacesare contracts that implementers must follow. Abstract classesallow contracts plus shared implementations - something that Interfaces cannot have. Classes can implement and inherit multiple interfaces. Classes can only extend a single abstract class.
接口是实现者必须遵守的契约。抽象类允许契约加上共享实现——这是接口不能拥有的。类可以实现和继承多个接口。类只能扩展一个抽象类。
Why Interface
为什么是接口
- You don't have default or shared code implementation
- You want to share data contracts (web services, SOA)
- You have different implementations for each interface implementer (
IDbCommandhasSqlCommandandOracleCommandwhich implement the interface in specific ways) - You want to support multiple inheritance.
- 您没有默认或共享的代码实现
- 您想要共享数据契约(Web 服务、SOA)
- 每个接口实现者都有不同的实现(
IDbCommand具有SqlCommand和OracleCommand以特定方式实现接口) - 您希望支持多重继承。
Why Abstract
为什么要抽象
- You have default or shared code implementation
- You want to minimize code duplication
- You want to easily support versioning
- 您有默认或共享的代码实现
- 您想最大程度地减少代码重复
- 您想轻松支持版本控制
回答by Jeff Watkins
With an interface you can do the following:
使用界面,您可以执行以下操作:
1) Create segregated interfaces which offer differing cuts of your implementation, allowing for a more cohesive interface.
1)创建分离的接口,提供不同的实现方式,允许一个更有凝聚力的接口。
2) Allow for multiple methods with the same name between interfaces, because hey, you have no conflicting implementation, just a signature.
2)允许接口之间有多个同名方法,因为嘿,你没有冲突的实现,只有一个签名。
3) You can version and hive off your interface independantly of your implementation, ensuring a contract is met.
3) 你可以独立于你的实现来版本化和分离你的接口,确保满足合同。
4) Your code can rely on abstraction rather than concretion, allowing for smart dependency injection, including injecting test Mocks etc.
4) 你的代码可以依赖抽象而不是具体,允许智能依赖注入,包括注入测试 Mocks 等。
There are many more reasons I'm sure, these are just a few.
我敢肯定还有更多的原因,这些只是其中的几个。
An abstract class allows you to have a partially concrete base to work from, this is not the same as an interface but has its own qualities such as the ability to create partial implementation using the template method pattern.
抽象类允许你有一个部分具体的基础来工作,这与接口不同,但有它自己的特性,比如使用模板方法模式创建部分实现的能力。
回答by Tony Hopkinson
Both abstract class and interface are contracts.
抽象类和接口都是契约。
The idea of a contract is you specify some behavior. If you say you've implemented you've agreed to the contract.
契约的想法是你指定一些行为。如果你说你已经实施了,你就同意了合同。
The choice of abstract over interrface is.
抽象而不是接口的选择是。
Any non abstract descendant of the abstract class will implement the contract.
抽象类的任何非抽象后代都将实现契约。
versus
相对
Any class that implements the interface will implement the contract.
任何实现接口的类都将实现契约。
So you use abstract when you want to specify some behavior all descendants must implement and save yourself defining a separate interface, but now everything that meets this effectively aggregated contract must be a descendant.
因此,当您想要指定所有后代必须实现的某些行为并保存自己定义一个单独的接口时,您可以使用抽象,但是现在满足这个有效聚合契约的所有内容都必须是后代。
回答by Manoj
Abstract class are crated for related entities where as Interfaces can be used for unrelated entities.
抽象类是为相关实体创建的,而接口可用于不相关的实体。
For e.g if I have two entities say Animal and Human then i will go for Interface where as if i have to go in detail say Tiger,lion and want to relate with Animal then will choose Animal Abstract class..
例如,如果我有两个实体,例如 Animal 和 Human,那么我将选择 Interface,就好像我必须详细说 Tiger,lion 并且想要与 Animal 相关,然后将选择 Animal Abstract 类。
will look like below
看起来像下面
Interface
____|____
| |
Animal Human
Animal (Abstract class)
__|___
| |
Tiger Lion
回答by Gabriel C. Troia
In one word - because of Polymorphism!
一句话——因为多态!
If you "Program to an Interface, not an Implementation" than you can inject different objects which share the same interface(type) into the method as an argument. This way your method code is not coupled with any implementation of another class which means it's always open to work with newly created objects of the same interface. (Open/Close Principle)
如果您“为接口编程,而不是实现”,那么您可以将共享相同接口(类型)的不同对象作为参数注入到方法中。这样您的方法代码就不会与另一个类的任何实现耦合,这意味着它始终可以使用相同接口的新创建的对象。(开闭原则)
- Look into Dependency Injection and definitely read Design Patterns - Elements of Reusable Object-Oriented Softwareby GOF.
- 研究依赖注入,一定要阅读GOF 的Design Patterns - Elements of Reusable Object-Oriented Software。

