答案是多态和多态 :如果你声明一堆类b / b实现相同的接口,那么你可以编写代码 ,可以对任何这些类进行操作,因为代码知道 它们都使用相同的调用实现相同的接口方法 序列(签名)。作为一个(愚蠢的)例子,如果我有一个 接口: 公共接口IGreeting { public string Hello {get; } public void ShakeHands(); } 我写了几个课: 公共类英语:IGreeting { public string Hello {get {return" Hello" ;; } $ public void ShakeHands(){//在这里做一些事情} } 公共类西班牙语:IGreeting { 公共字符串Hello {get {return"Buenosdías" ;; } $ public void ShakeHands(){//在这里做一些事情} } 然后我可以写一个方法在其他一些课程中: public void SayHello(IGreeting person) { Console.WriteLine(person.Hello); person.ShakeHands(); } " SayHello"可以打招呼和握手,而不知道它是什么样的人,因为它知道传递给它的所有对象必须实现IGreeting界面,所以必须有a你好 string property and aShakeHands"没有参数的方法。 没有界面,就没有办法表达,一个对象 有一个Hello字符串属性和一个ShakeHands无效的方法, 不带参数。 (顺便说一句,关于术语的挑剔细节:接口_declares_ 属性,方法和事件。这个类要么_implements_他们 或_defines_他们(他们俩都是同样的东西,真的)。是的, 类也再次声明它们,但这并不像它实现它们的想法那么重要。) The answer is something called "polymorphism": if you declare a bunchof classes as implementing the same interface, then you can write codethat can operate on any of those classes, because the code knows thatthey all implement the same interface methods with the same callingsequences (signatures). As a (stupid) example, if I were to have aninterface: public interface IGreeting{public string Hello { get; }public void ShakeHands();} and I write a couple of classes: public class English : IGreeting{public string Hello { get { return "Hello"; } }public void ShakeHands() { // Do some stuff here }} public class Spanish : IGreeting{public string Hello { get { return "Buenos días"; } }public void ShakeHands() { // Do some stuff here }} then I could write a method in some other class: public void SayHello(IGreeting person){Console.WriteLine(person.Hello);person.ShakeHands();} "SayHello" can say hello and shake hands without knowing what kind ofperson it is, because it knows that all objects passed to it mustimplement the IGreeting interface, and so must have a "Hello" stringproperty and a "ShakeHands" method that takes no arguments. Without the interface, there would be no way to express, "An objectthat has a Hello string property and a ShakeHands void method thattakes no arguments." (By the way, a picky detail about terminology: the interface _declares_the properties, methods, and events. The class either _implements_ themor _defines_ them (they both mean the same thing, really). Yes, theclass also declares them again, but that''s not so important as the ideathat it implements them.) 这篇关于界面问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-30 00:38