我们为什么要使用接口?它仅用于标准化吗?

我们为什么要使用接口?

它仅用于标准化吗?


白板的微信
浏览 489回答 3
3回答

茅侃侃

接口用于描述已实现的功能。因此,您可以将实现同一接口的多个对象视为该接口的类型。例如:public interface IMyInterface{&nbsp; &nbsp; public void DoFirst();&nbsp; &nbsp; public int DoSecond();}public class A : IMyInterface{&nbsp; &nbsp;//class has to implement DoFirst and DoSecond&nbsp; &nbsp;public void DoFirst(){&nbsp; &nbsp; &nbsp;Console.WriteLine("Blubb1");&nbsp;&nbsp;&nbsp; &nbsp;}&nbsp; &nbsp;public int DoSecond(){&nbsp; &nbsp; &nbsp;Console.WriteLine("Blubb2");&nbsp; &nbsp; &nbsp;return 2;&nbsp;&nbsp;&nbsp; &nbsp;}}public class B : IMyInterface{&nbsp; &nbsp;//class has to implement DoFirst and DoSecond&nbsp; &nbsp;public void DoFirst(){&nbsp; &nbsp; &nbsp;Console.WriteLine("Blibb1");&nbsp;&nbsp;&nbsp; &nbsp;}&nbsp; &nbsp;public int DoSecond(){&nbsp; &nbsp; &nbsp;Console.WriteLine("Blibb2");&nbsp;&nbsp;&nbsp; &nbsp; &nbsp;return 4;&nbsp; &nbsp;}}这些类以几种方式实现Interface。但是您可以将它们用作IMyInterface。例如:public static void DoMethodsInInterface(IMyInterface inter){&nbsp; &nbsp; inter.DoFirst();&nbsp; &nbsp; inter.DoSecond();}public static void main(){&nbsp; &nbsp;DoMethodsInInterface(new A());&nbsp; &nbsp;DoMethodsInInterface(new B());&nbsp; &nbsp;//Or use it in a List&nbsp; &nbsp;List<IMyInterface> interlist = new List<IMyInterface>();&nbsp; &nbsp;interlist.Add(new A());&nbsp; &nbsp;interlist.Add(new B());&nbsp; &nbsp;foreach(IMyInterface inter in interlist){&nbsp; &nbsp; &nbsp; inter.DoFirst();&nbsp; &nbsp;}}我希望这可以弄清楚为什么接口有用。

梵蒂冈之花

这是高级视图...接口在信息隐藏的概念中起着重要作用。它们基本上可以帮助您隐藏类的实现细节,以便调用类不会依赖于该实现。因此,通过使用接口,您可以在不更改调用类的情况下修改实现。这反过来又限制了代码的复杂性,从长远来看使维护起来更容易。当我第一次开始理解界面时,它们被解释为“提供类描述的合同”。不知道这会帮助你,但如果你认为一个接口的一辆汽车,你可以说,它驱动,休息,并打开。因此,只要它使我从A点到达B点,我实际上就不必知道如何实现这些功能。
打开App,查看更多内容
随时随地看视频慕课网APP