我正在使用各种对象在ASP.NET/VB.NET中构建一个体面的应用程序...我之前从未使用过接口,当我向他提到这个时,一位程序员也不愿意这样做.任何人都可以快速概述一下它们的使用方法,它们的用途以及我使用它们的原因吗?也许我不需要在这个项目中使用它们,但如果它们有所帮助,我肯定会喜欢尝试.
非常感谢!
一旦你"获得"接口,OOP就会真正落到实处.简单地说,一个接口定义了一组公共方法签名,你创建了一个实现这些方法的类.这允许您为实现特定接口的任何类(即具有相同方法的类)概括函数,即使这些类不一定相互下降.
Module Module1 Interface ILifeform ReadOnly Property Name() As String Sub Speak() Sub Eat() End Interface Class Dog Implements ILifeform Public ReadOnly Property Name() As String Implements ILifeform.Name Get Return "Doggy!" End Get End Property Public Sub Speak() Implements ILifeform.Speak Console.WriteLine("Woof!") End Sub Public Sub Eat() Implements ILifeform.Eat Console.WriteLine("Yum, doggy biscuits!") End Sub End Class Class Ninja Implements ILifeform Public ReadOnly Property Name() As String Implements ILifeform.Name Get Return "Ninja!!" End Get End Property Public Sub Speak() Implements ILifeform.Speak Console.WriteLine("Ninjas are silent, deadly killers") End Sub Public Sub Eat() Implements ILifeform.Eat Console.WriteLine("Ninjas don't eat, they wail on guitars and kick ass") End Sub End Class Class Monkey Implements ILifeform Public ReadOnly Property Name() As String Implements ILifeform.Name Get Return "Monkey!!!" End Get End Property Public Sub Speak() Implements ILifeform.Speak Console.WriteLine("Ook ook") End Sub Public Sub Eat() Implements ILifeform.Eat Console.WriteLine("Bananas!") End Sub End Class Sub Main() Dim lifeforms As ILifeform() = New ILifeform() {New Dog(), New Ninja(), New Monkey()} For Each x As ILifeform In lifeforms HandleLifeform(x) Next Console.ReadKey(True) End Sub Sub HandleLifeform(ByVal x As ILifeform) Console.WriteLine("Handling lifeform '{0}'", x.Name) x.Speak() x.Eat() Console.WriteLine() End Sub End Module
上面没有一个类相互下降,但是我的HandleLifeform方法被推广到对所有类进行操作 - 或者实际上是任何实现ILifeform接口的类.