C# 实现接口的好处
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1389434/
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
Benefits of implementing an interface
提问by DNR
what are the benefits of implementing an interface in C# 3.5 ?
在 C# 3.5 中实现接口有什么好处?
采纳答案by Mehrdad Afshari
You'll be able to pass your object to a method (or satisfy a type constraint) that expects the interface as an argument. C# does not support "duck typing." Just by writing the methods defined by the interface, the object will not automatically be "compatible" with the interface type:
您将能够将对象传递给需要接口作为参数的方法(或满足类型约束)。C# 不支持“鸭子类型”。仅仅通过编写接口定义的方法,对象不会自动与接口类型“兼容”:
public void PrintCollection<T>(IEnumerable<T> collection) {
foreach (var x in collection)
Console.WriteLine(x);
}
If List<T>
did not implement the IEnumerable<T>
interface, you wouldn't be able to pass it as an argument to PrintCollection
method (even if it had a GetEnumerator
method).
如果List<T>
没有实现IEnumerable<T>
接口,您将无法将其作为参数传递给PrintCollection
方法(即使它有GetEnumerator
方法)。
Basically, an interface declares a contract. Implementing an interface enforces your class to be bound to the contract (by providing the appropriate members). Consequently, everything that relies on that contract (a method that relies on the functionality specified by the interface to be provided by your object) can work with your object too.
基本上,一个接口声明了一个契约。实现接口强制您的类绑定到契约(通过提供适当的成员)。因此,依赖于该契约的所有内容(依赖于由您的对象提供的接口指定的功能的方法)也可以与您的对象一起使用。
回答by Daniel Elliott
It will help when you try to:
当您尝试执行以下操作时,它会有所帮助:
- Unit test with Stubs / Mocks
- Implement Dependency injection
- Solve world hunger (although this unproven!)
- 使用 Stubs / Mocks 进行单元测试
- 实现依赖注入
- 解决世界饥饿问题(尽管未经证实!)
Kindness,
善良,
Dan
担
回答by Chris Gill
You aren't tied to class inheritance - you can apply an interface to any class. Any class can have multiple interfaces - C# doesn't support multiple class inheritance, i.e. you are providing a good abstraction layer through the interface
您不受类继承的束缚 - 您可以将接口应用于任何类。任何类都可以有多个接口 - C# 不支持多个类继承,即您通过接口提供了一个很好的抽象层
回答by Jorge Córdoba
The main benefit is about code readability, code maintainability and code "semantics".
主要好处是代码可读性、代码可维护性和代码“语义”。
- Code readability:An interface constitutes a declaration about intentions. It defines a capability of your class, what your class is capable of doing. If you implement ISortable you're clearly stating that your class can be sorted, same for IRenderable or IConvertible.
- Code semantics:By providing interfaces and implementing them you're actively separating concepts in a similar way HTML and CSS does. A class is a concrete implementation of an "object class" some way of representing the reality by modeling general properties of real life objects or concepts. An interface define a behavioral model, a definition of what an object can do. Separating those concepts keeps the semantics of your code more clear. That way some methods may need an instance of an animal class while other may accept whatever object you throw at them as long as it supports "walking".
- Code maintainability:Interfaces helps to reduce coupling and therefore allow you to easily interchange implementations for the same concept without the underlying code being affected. You can change the implementation of a IMessage easily by defining a new class that implements the interface. Compare that to sistematically replacing all references from CMessage to CMyNewMessageClass.
- 代码可读性:接口构成了关于意图的声明。它定义了你的类的能力,你的类能够做什么。如果你实现了 ISortable,你就清楚地表明你的类可以被排序,对于 IRenderable 或 IConvertible 也是如此。
- 代码语义:通过提供接口并实现它们,您以类似于 HTML 和 CSS 的方式主动分离概念。类是“对象类”的具体实现,它通过对现实生活对象或概念的一般属性进行建模来表示现实。一个接口定义了一个行为模型,一个对象可以做什么的定义。分离这些概念可以使代码的语义更加清晰。这样一些方法可能需要一个动物类的实例,而其他方法可能会接受你扔给它们的任何对象,只要它支持“行走”。
- 代码可维护性:接口有助于减少耦合,因此允许您轻松交换同一概念的实现,而不会影响底层代码。您可以通过定义一个实现接口的新类来轻松更改 IMessage 的实现。将其与系统地替换从 CMessage 到 CMyNewMessageClass 的所有引用进行比较。
回答by Philippe
An interface defines a contract (things that an object is able to do), while a concrete class (or struct) defines the concrete behavior.
接口定义了契约(对象能够做的事情),而具体的类(或结构)定义了具体的行为。
For an example, IList is an interface, it defines the methods that a concrete object has to provide in order to be used like any other object implementing IList. Everywhere an IList can be used, your object that implements IList can be used as well. The way you concretely implement it and the way your object behaves when those IList methods are called is left to you.
例如,IList 是一个接口,它定义了具体对象必须提供的方法,以便像实现 IList 的任何其他对象一样使用。在可以使用 IList 的任何地方,也可以使用实现 IList 的对象。具体实现它的方式以及调用这些 IList 方法时对象的行为方式由您决定。
回答by Sivakumar
An Interface is a reference type and it contains only abstract members. Interface's members can be Events, Methods, Properties and Indexers. But the interface contains only declaration for its members. Any implementation must be placed in class that realizes them. The interface can't contain constants, data fields, constructors, destructors and static members. All the member declarations inside interface are implicitly public.
接口是一种引用类型,它只包含抽象成员。接口的成员可以是事件、方法、属性和索引器。但是接口只包含其成员的声明。任何实现都必须放在实现它们的类中。接口不能包含常量、数据字段、构造函数、析构函数和静态成员。interface 中的所有成员声明都是隐式公开的。
回答by TJPowell
Interfaces provide no actual advantage. Anything that can be done with an interface can, and should be done using other language constructions. Multiple inheritance is oft quoted as the only REAL benefit derived from using interfaces, but I can do multiple inheritance quite easily and clearly in C# - I do it every day. Changing the code without "breaking" the interface is the silliest of all excuses... That applies the same to concrete classes as it does to abstract classes or interfaces. As long as the functional signature does not change, you haven't broken the interface. Doesn't matter where it was declared. Simply putting a functional prototype in a separate file and naming it with an "I" in front buys nothing - except that you end up with twice as many source files to maintain. The supposition that the interface is defined early, and then maintains the contract is ridiculous. Interface methods and their parameters change ALL the time, because everything is never known up-front. That's why MicroSof stopped using them long ago. They had IUnKnown, IUnknown2, etc. It created a mess.
接口没有提供实际优势。可以使用接口完成的任何事情都可以并且应该使用其他语言结构来完成。多重继承经常被引用为使用接口带来的唯一真正好处,但我可以在 C# 中非常轻松和清晰地进行多重继承 - 我每天都这样做。在不“破坏”接口的情况下更改代码是所有借口中最愚蠢的......这适用于具体类,也适用于抽象类或接口。只要功能签名没有改变,你就没有破坏接口。在哪里声明都没有关系。简单地将一个功能原型放在一个单独的文件中,并在前面用“I”命名它没有任何意义——除了你最终要维护的源文件数量是原来的两倍。提前定义接口,然后维护契约的假设是荒谬的。接口方法及其参数一直在变化,因为一切都是事先未知的。这就是 MicroSof 很久以前就停止使用它们的原因。他们有 IUnKnown、IUnknown2 等。它造成了混乱。
回答by TJPowell
If you work in a huge, commercial software house - you MIGHT want to consider the judicial use of Interfaces. Otherwise, you should stay away from them. Same for multi-threading. If I see one more script-kiddie app that spawns 20 threads to write "Hello World" I'm gonna freak. Multi-threading should be completely reserved for apps that require it, usually in a multi-processing environment. 90% of the time it causes more harm than good. And don't bother with the thread highHyman / off-topic comments. I don't care. I've been doing this longer than most of you have been alive. Rank has its privileges.
如果你在一个巨大的商业软件公司工作——你可能想考虑接口的司法用途。否则,你应该远离他们。多线程也一样。如果我再看到一个脚本小子应用程序产生 20 个线程来编写“Hello World”,我会发疯的。多线程应该完全保留给需要它的应用程序,通常在多处理环境中。90% 的情况下,它弊大于利。并且不要打扰线程劫持/偏离主题的评论。我不在乎。我做这件事的时间比你们大多数人还活着的时间都长。Rank有它的特权。
回答by Jiten
The main benefits of interfaces is mostly related to project design.
接口的主要好处大多与项目设计有关。
If you use an interface:
如果使用接口:
- The consumer of the interface should implement that interface.
- Designing bridge patters.
- Creating a contract so that user must adhere the rules of the interface.
- Can take only interface part (
Object
) from the main class. - Even class is private, can obtain the interface object from that
- Multiple inheritance kind of style.
- Need not be should implement, simple go for if implements that means if you want you can implement other wise can drop it..
- Cleaner code.
- Implementation which changes depends on class can go ahead with interface.
- If each class have separate implementation of a method better to go for interfaces. For example
IEnumerable
in collections.
- 接口的使用者应该实现该接口。
- 设计桥梁模式。
- 创建合同,以便用户必须遵守界面规则。
- 只能
Object
从主类中获取接口部分 ( )。 - 即使类是私有的,也可以从中获取接口对象
- 多继承类样式。
- 不需要应该实现,简单的去如果实现意味着如果你想要你可以实现其他明智的可以放弃它..
- 更干净的代码。
- 改变依赖于类的实现可以继续接口。
- 如果每个类都有一个方法的单独实现,那么最好使用接口。例如
IEnumerable
在集合中。
According to C# Architect, in a simple word it's a contract. Consumer must adhere to it.
根据 C# 架构师的说法,简单来说,它是一种合同。消费者必须遵守。
回答by Tone ?koda
The way I understand it interfaces are most useful in these cases:
我理解它的方式接口在这些情况下最有用:
Cleaner division of labor among programmers. Lead programmer writes interface and junior programmer writes its implementation. That makes perfect sense to me. Lead programmer could write pseudocode instead of interface though.
Some specific situation, where you need 2 or more different implementations of the same class, for example interface animal and classes tiger and lion that use it. And even here it doesn't makes much sense, because lions and tigers share some things in common. Abstract class would be better, because if you use interface you have to write common functions in separate classes which leads to code duplication, which is bad.
You write a library and want it to be modifiable by users. So you write interface and its class implementation. User of your lib still has the possibility to write his own implementation class, which may use different technology/algorithm which achieves the same result, but maybe in a faster way for example. This is also the reason why we meet so many interfaces in libs we use, but rarely feel the need to write our own interfaces. Because we don't write libraries.
程序员之间更清晰的分工。首席程序员编写接口,初级程序员编写其实现。这对我来说很有意义。不过,首席程序员可以编写伪代码而不是接口。
在某些特定情况下,您需要同一个类的 2 个或更多不同的实现,例如接口动物和使用它的类老虎和狮子。即使在这里也没有多大意义,因为狮子和老虎有一些共同点。抽象类会更好,因为如果您使用接口,则必须在单独的类中编写公共函数,这会导致代码重复,这很糟糕。
您编写了一个库并希望它可以被用户修改。所以你编写接口及其类实现。你的库的用户仍然有可能编写自己的实现类,它可能使用不同的技术/算法来实现相同的结果,但例如可能以更快的方式。这也是我们在使用的libs中遇到这么多接口,却很少觉得需要自己写接口的原因。因为我们不写库。