用戶可以在vb.net中使用接口來完成多態性的實現。通過使用多接口,用戶可以在不中斷運行代碼的情況下,允許運行多種軟件的系統組件。
接口象類那樣描述屬性和方法,但是它和類不同的是,接口不能提供任何implementation。
為了使用接口來實現多態性,用戶需先建立一個接口,並且通過其他的幾個類實現該接口。用戶可以用幾乎相同的方法調用其他對象已經實現的方法。
下面這個例子就是使用接口的方法實現多態性:
Namespace PolyNamespace Interface Animal Sub Move(ByRef Distance As Double) Sub Bite(Byval What As Object) End Interface Class Flea Implements animal Public Sub bite(Byval What As Object)Implements animal.bite 'Bite something End Sub Sub Move(ByRef Distance AS Double)Implements animal.move distance=Distance+1 End Sub End Class Class Dog Implements animal Public Sub bite(Byval What As Object)Implements animal.bite 'Bite something End Sub Sub Move(ByRef Distance AS Double)Implements animal.move distance=Distance+100 End sub End Class End Namespace 'add this section to the your form Protected Sub Button1_Click(Byval sender As System.Object,_ Byval e As System.EventArgs) Dim aFlea As New Flea() Dim anobj As Object() Dim aDog As New Dog() GetFood(aflea,anobj) GetFood(aDog,anobj) End Sub Public sub GetFood(Byval Critter As Animal,Byval Food As Object) Dim dblDistance As Double 'Code to calculate distance to food(omitted). Critter.Move(dblDistance) 'Early bound(vtable) Critter.Bite(Food) 'Early bound(vtable) End Sub