VB.NET接口實(shí)現(xiàn)多態(tài)實(shí)際代碼編寫
VB.NET編程語(yǔ)言為我們帶來(lái)了非常大的好處。而且其作為一項(xiàng)面向?qū)ο笳Z(yǔ)言,也有很多新的功能供大家使用。比如在多態(tài)性的實(shí)現(xiàn)方面就有很多方法。今天我們先來(lái)一起學(xué)習(xí)其中VB.NET接口實(shí)現(xiàn)多態(tài)的具體操作步驟。#t#
VB.NET接口實(shí)現(xiàn)多態(tài)的實(shí)現(xiàn),能夠通過使用多接口,用戶可以在不中斷運(yùn)行代碼的情況下,允許運(yùn)行多種軟件的系統(tǒng)組件。
接口象類那樣描述屬性和方法,但是它和類不同的是,接口不能提供任何implementation。
為了正確的操作VB.NET接口實(shí)現(xiàn)多態(tài),用戶需先建立一個(gè)接口,并且通過其他的幾個(gè)類實(shí)現(xiàn)該接口。用戶可以用幾乎相同的方法調(diào)用其他對(duì)象已經(jīng)實(shí)現(xiàn)的方法。
下面這個(gè)例子就是VB.NET接口實(shí)現(xiàn)多態(tài):
- 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
VB.NET接口實(shí)現(xiàn)多態(tài)的具體代碼編寫方式就為大家介紹到這里。