简体   繁体   English

使用Interface有什么好处?

[英]What is the advantage of using Interface?

What is the use of using Interface? 使用Interface有什么用?

I heard that it is used instead of multiple inheritance and data-hiding can also be done with it. 我听说它被用来代替多重继承,数据隐藏也可以用它来完成。

Is there any other advantage, where are the places interface is used, and how can a programmer identify that interface is needed? 是否还有其他优点,使用places接口的位置,以及程序员如何识别需要的接口?

What is the difference between explicit interface implementation and implicit interface implementation ? explicit interface implementationimplicit interface implementation什么区别?

To tackle the implicit/explicit question, let's say that two different interfaces have the same declaration: 为了解决隐式/显式问题,让我们说两个不同的接口具有相同的声明:

interface IBiographicalData

    {
       string LastName
       {
          get;
          set;
       }

    }

    interface ICustomReportData
    {
       string LastName
       {
          get;
          set;
       }
    }

And you have a class implementing both interfaces: 你有一个实现两个接口的类:

class Person : IBiographicalData, ICustomReportData
{
    private string lastName;

    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
}

Class Person Implicitly implements both interface because you get the same output with the following code: 类Person 隐式实现两个接口,因为您使用以下代码获得相同的输出:

Person p = new p();
IBiographicalData iBio = (IBiographicalData)p;
ICustomReportData iCr = (ICustomReportData)p;

Console.WriteLine(p.LastName);
Console.WriteLine(iBio.LastName);
Console.WriteLine(iCr.LastName);

However, to explicitly implement, you can modify the Person class like so: 但是,要显式实现,您可以像这样修改Person类:

class Person : IBiographicalData, ICustomReportData
{
    private string lastName;

    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }

    public string ICustomReportData.LastName
    {
        get { return "Last Name:" + lastName; }
        set { lastName = value; }
    }
}

Now the code: 现在的代码:

Console.WriteLine(iCr.LastName);

Will be prefixed with "Last Name:". 将以“姓氏:”为前缀。

http://blogs.msdn.com/b/mhop/archive/2006/12/12/implicit-and-explicit-interface-implementations.aspx http://blogs.msdn.com/b/mhop/archive/2006/12/12/implicit-and-explicit-interface-implementations.aspx

Interfaces are very useful for 接口非常有用

  • Dependency Injection 依赖注入
  • Inversion of Control 控制反转
  • Test Isolation 测试隔离

An interface simply separates the description of a class API from its implementation. 接口只是简单地将类API的描述与其实现分开。 It's about separation of concerns which is fundamental to any robust software project. 它是关于关注点的分离,这是任何强大的软件项目的基础。 You can replace the implementing classes without breaking any other code. 您可以在不破坏任何其他代码的情况下替换实现类。

One area where this is particularly helpful is with unit testing, as it allows you to mock out the interfaces that you don't want to test as part of a given test case. 这一点特别有用的一个方面是单元测试,因为它允许您模拟出您不想作为给定测试用例的一部分进行测试的接口。

Having entirely unrelated classes implement the same interface also allows you to write methods that can operate on different classes in different hierarchies (ie no common ancestor other than object), without them having to take object as their type. 具有完全不相关的类实现相同的接口还允许您编写可以在不同层次结构中的不同类上操作的方法(即除了对象之外没有共同的祖先),而不必将对象作为其类型。 For example you can write a method that takes IEnumerable, and pass it List, Array etc. Without interfaces or a common base type this wouldn't be possible (except by casting from object). 例如,您可以编写一个采用IEnumerable的方法,并将其传递给List,Array等。如果没有接口或公共基类型,则无法实现(除非通过从对象转换)。

IN the most basic of terms, we get back to OOP 101: 从最基本的术语来看,我们回到OOP 101:

Inheritance: Object B "is a" type of Object A. Behaviours and methods implemented by Object A are inherited, implementation and all (with some room for Overriding) by Object B. 继承:对象B“是对象A的类型。对象A实现的行为和方法是对象B的继承,实现和所有(有一些覆盖空间)。

Interface: Object A and Object B both "Act Like" examples of an abstract object represented by a common interface. 接口:对象A和对象B都是由“公共接口”表示的抽象对象的“Act Like”示例。 James Gaunt uses the example if Ienumerable above. James Gaunt使用了上面的Ienumerable示例。 Other examples might be IPrintable, IDisposable, Etc. 其他示例可能是IPrintable,IDisposable等。

For any given class which implements these Interfaces, the implementation is liable to be quite different (Think about how you implment IDisposable in different classes which utilize a dispose method). 对于任何实现这些接口的给定类,实现都可能完全不同(想想你如何在使用dispose方法的不同类中实现IDisposable)。 However, client code does not need to know or care what the actual object's type is - the code can simply access the desired properties and methods through the interface. 但是,客户端代码不需要知道或关心实际对象的类型 - 代码可以通过接口简单地访问所需的属性和方法。

Inheritance is often seen as a "magic" answer to a good many coding problems, but is also widely mis-used as a means to avoid wriing more code. 继承通常被视为许多编码问题的“神奇”答案,但也被广泛误用作避免编写更多代码的手段。 I disagree with user492238 that things done with Interfaces can be just as easily done through inheritance. 我不同意user492238,使用Interfaces完成的事情可以通过继承轻松完成。 Such an approach will often box you into a corner. 这种方法通常会让你陷入困境。 And, as Jodrell observes, multiple inheritance is not a feature of .net (and rightfully so, in my opinion). 并且,正如Jodrell所观察到的,多重继承不是.net的特征(在我看来这是正确的)。

When you find yourself implementing the same behavior across several (or many) otherwise unrelated classes, consider defining an interface which provides the API for that behavior. 当您发现自己在几个(或许多)其他不相关的类中实现相同的行为时,请考虑定义一个为该行为提供API的接口。 You may have several classes: Person, Animal, Building, Etc. All of which may require a method to provide printable output. 您可能有几个类:Person,Animal,Building等。所有这些类都可能需要一种方法来提供可打印的输出。 You may also have a method which accepts IPrintableObject as a parameter. 您可能还有一个接受IPrintableObject作为参数的方法。 IN this case, you can implement IPrintableObject within any of the classes you need to print, provide the implementation code within each of those objects, and feed them to the client code. 在这种情况下,您可以在需要打印的任何类中实现IPrintableObject,在每个对象中提供实现代码,并将它们提供给客户端代码。

That's probably more a question to more experienced programmers than an answer, but... For most of the time I was working with small team and we were close, knowing each other well. 对于经验丰富的程序员而言,这可能是一个问题,而不是答案,但是...在大多数情况下,我与小团队合作,我们很亲密,彼此了解得很好。 And I was wondering what for interfaces really are. 我想知道界面到底是什么。 But my last project was with new team and was little bigger. 但我的最后一个项目是新团队,而且规模更大。 And it was a holly mess. 这是一个冬青混乱。 And after some time I came to conclusion: we should use interfaces. 过了一段时间我得出结论:我们应该使用接口。

Not as a way to solve any technical issues, but as a kind of design doc, which is in code, which force you to follow this design, which is hard to ignore, which would make cooperation 100 times easier. 不是解决任何技术问题的方法,而是作为一种代码中的设计文档,它迫使您遵循这种难以忽视的设计,这将使协作变得容易100倍。 It's not problem to sit together and came up with interface. 坐在一起想出界面并不是问题。 And then you can split and implement stuff alone. 然后你可以分开并单独实现一些东西。 But if you follow interface, then every other person in team can much more clearly read the class idea. 但是如果你按照界面进行操作,那么团队中的每个人都可以更清楚地阅读课堂理念。

So, my best guess, is that interfaces is really nice way for arranging cooperation: implement however you want, but no any public interface outside of interfaces, and rewriting interfaces must be done with others involved. 所以,我最好的猜测是,接口是安排合作的好方法:实现你想要的,但是接口之外没有任何公共接口,重写接口必须与其他人一起完成。 Easy way to keep code in order and separating common stuff, and yours only stuff. 简单的方法来保持代码的顺序和分离常见的东西,而你的东西只是你的东西。

Most - if not all - things which can be done with interfaces could just as well get done via inheritance. 大多数 - 如果不是全部 - 可以通过接口完成的事情也可以通过继承来完成。 Interfaces can be used to replace a class design using abstract base classes. 接口可用于使用抽象基类替换类设计。 Which to prefer is mostly a matter of personal experience and taste. 更喜欢哪个主要是个人经验和品味。 (Of course there are people which state very strict rules about when to prefer the one above the other). (当然,有些人对于什么时候更喜欢一个在另一个之上而制定了非常严格的规则)。

And there do frameworks exist (often in conjunction to DI containern) which force you to use interfaces. 并且存在框架(通常与DI containern结合),这会强制您使用接口。

An interface is a contract; 界面是合同; it's a guarantee that the methods and properties specified will be available. 它保证指定的方法和属性可用。 It provides no implementation, which is what makes it different than a class which does provide implementation. 它没有提供任何实现,这使得它与提供实现的类不同。

Interfaces are the highest level of abstraction, it provides no implementation details to the consumer. 接口是最高级别的抽象,它不向消费者提供实现细节。

Interfaces are almost semantically equivalent to pure abstract classes (classes that don't provide any implementation). 接口几乎在语义上等同于纯抽象类(不提供任何实现的类)。 In c#, vb.net and other languages, classes can have multiple interfaces, but only one base class. 在c#,vb.net和其他语言中,类可以有多个接口,但只有一个基类。 So for a specific advantage interfaces have over classes (abstract or otherwise) is that you can implement multiple interfaces, but only inherit from one class. 因此,对于特定的优点,接口具有过类(抽象或其他),您可以实现多个接口,但只能从一个类继承。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM