VB.Net類和物件


當定義一個類時,就定義了一個資料型別的藍圖(或模板)。這實際上並沒有定義任何資料,但它確實定義了類名和含義,即該類的一個物件將包含哪些內容以及可以在這樣的物件上執行哪些操作。

物件是一個類的範例。構成類的方法和變數被稱為類的成員。

類定義

類定義以關鍵字Class開頭,後面跟著類名和類體,並以End Class語句結束。 以下是類定義的一般形式:

[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _
Class name [ ( Of typelist ) ]
    [ Inherits classname ]
    [ Implements interfacenames ]
    [ statements ]
End Class

其中,

  • attributelist 是適用於該類的屬性列表,這是一個可選項。
  • accessmodifier 定義了該類的存取級別,它的值有 - Public, Protected, Friend, Protected FriendPrivate,這是一個可選項。
  • Shadows 指示該變數在基礎類別中重新宣告並隱藏了一個相同名稱的元素或一組過載元素,這是一個可選項。
  • MustInherit 指定該類只能用作基礎類別,並且不能直接從它建立物件,即抽象類,這是一個可選項。
  • NotInheritable 指定該類不能用作基礎類別。
  • Partial 表示該類的定義部分。
  • Inherits 指定它所繼承的基礎類別。
  • Implements 指定類繼承的介面。

下面的例子演示了一個Box類,它有三個資料成員,分別是:length, breadthheight

Module mybox
   Class Box
      Public length As Double   ' Length of a box '
      Public breadth As Double   ' Breadth of a box '
      Public height As Double    ' Height of a box '
   End Class
   Sub Main()
      Dim Box1 As Box = New Box()        ' Declare Box1 of type Box '
      Dim Box2 As Box = New Box()        ' Declare Box2 of type Box '
      Dim volume As Double = 0.0     ' Store the volume of a box here '
      ' box 1 specification '
      Box1.height = 5.0
      Box1.length = 6.0
      Box1.breadth = 7.0
       ' box 2 specification '
      Box2.height = 10.0
      Box2.length = 12.0
      Box2.breadth = 13.0
      'volume of box 1 '
      volume = Box1.height * Box1.length * Box1.breadth
      Console.WriteLine("Volume of Box1 : {0}", volume)
      'volume of box 2 '
      volume = Box2.height * Box2.length * Box2.breadth
      Console.WriteLine("Volume of Box2 : {0}", volume)
      Console.ReadKey()
   End Sub
End Module

執行上面範例程式碼,得到以下結果 -

F:\worksp\vb.net\classes_objects>vbc mybox.vb
Microsoft (R) Visual Basic Compiler version 14.0.1038
for Visual Basic 2012
Copyright (c) Microsoft Corporation.  All rights reserved.
......
F:\worksp\vb.net\classes_objects>mybox.exe
Volume of Box1 : 210
Volume of Box2 : 1560

成員函式和封裝

一個類的成員函式是一個函式,它在類定義中具有其定義或原型,就像任何其他變數一樣。 它在它所屬的類的任何物件上執行,並且可以存取該物件的類的所有成員。

成員變數是一個物件的屬性(從設計的角度來看),它們是保密的,以實現封裝。 這些變數只能使用公共成員函式來存取。

讓我們來看看上面的概念設定和獲得不同類成員的值:

Module MemberFunctions
   Class Box
      Public length As Double   ' Length of a box '
      Public breadth As Double   ' Breadth of a box'
      Public height As Double    ' Height of a box'
      Public Sub setLength(ByVal len As Double)
          length = len
      End Sub
      Public Sub setBreadth(ByVal bre As Double)
          breadth = bre
      End Sub
      Public Sub setHeight(ByVal hei As Double)
          height = hei
      End Sub
      Public Function getVolume() As Double
          Return length * breadth * height
      End Function
   End Class
   Sub Main()
      Dim Box1 As Box = New Box()        ' Declare Box1 of type Box'
      Dim Box2 As Box = New Box()        ' Declare Box2 of type Box'
      Dim volume As Double = 0.0     ' Store the volume of a box here'

     ' box 1 specification'
      Box1.setLength(6.0)
      Box1.setBreadth(7.0)
      Box1.setHeight(5.0)

      'box 2 specification'
      Box2.setLength(12.0)
      Box2.setBreadth(13.0)
      Box2.setHeight(10.0)

      ' volume of box 1'
      volume = Box1.getVolume()
      Console.WriteLine("Volume of Box1 : {0}", volume)

      'volume of box 2'
      volume = Box2.getVolume()
      Console.WriteLine("Volume of Box2 : {0}", volume)
      Console.ReadKey()
   End Sub
End Module

執行上面範例程式碼,得到以下結果 -

F:\worksp\vb.net\classes_objects>vbc MemberFunctions.vb
Microsoft (R) Visual Basic Compiler version 14.0.1038
for Visual Basic 2012
Copyright (c) Microsoft Corporation.  All rights reserved.
F:\worksp\vb.net\classes_objects>MemberFunctions.exe
Volume of Box1 : 210
Volume of Box2 : 1560

建構函式和解構函式

一個類別建構函式是一個類的特殊成員子程式,每當建立這個類的新物件的時候建構函式就會被執行。一個建構函式名稱為:New,它沒有任何返回型別。

以下程式演示了建構函式的概念和使用:

Module MemberFunctions
   Class Box
      Public length As Double   ' Length of a box '
      Public breadth As Double   ' Breadth of a box'
      Public height As Double    ' Height of a box'
      Public Sub setLength(ByVal len As Double)
          length = len
      End Sub
      Public Sub setBreadth(ByVal bre As Double)
          breadth = bre
      End Sub
      Public Sub setHeight(ByVal hei As Double)
          height = hei
      End Sub
      Public Function getVolume() As Double
          Return length * breadth * height
      End Function
   End Class
   Sub Main()
      Dim Box1 As Box = New Box()        ' Declare Box1 of type Box'
      Dim Box2 As Box = New Box()        ' Declare Box2 of type Box'
      Dim volume As Double = 0.0     ' Store the volume of a box here'

     ' box 1 specification'
      Box1.setLength(6.0)
      Box1.setBreadth(7.0)
      Box1.setHeight(5.0)

      'box 2 specification'
      Box2.setLength(12.0)
      Box2.setBreadth(13.0)
      Box2.setHeight(10.0)

      ' volume of box 1'
      volume = Box1.getVolume()
      Console.WriteLine("Volume of Box1 : {0}", volume)

      'volume of box 2'
      volume = Box2.getVolume()
      Console.WriteLine("Volume of Box2 : {0}", volume)
      Console.ReadKey()
   End Sub
End Module

執行上面範例程式碼,得到以下結果 -

F:\worksp\vb.net\classes_objects>vbc Line.vb
Microsoft (R) Visual Basic Compiler version 14.0.1038
for Visual Basic 2012
Copyright (c) Microsoft Corporation.  All rights reserved.
......
F:\worksp\vb.net\classes_objects>Line.exe
Object is being created
Length of line : 6

預設的建構函式沒有任何引數,但是如果需要的話,建構函式可以有引數。這樣的建構函式被稱為引數化的建構函式。這種技術可以在建立物件時將初始值賦值,如以下範例所示:

Class Line2
   Private length As Double    ' Length of a line '
   Public Sub New(ByVal len As Double)   'parameterised constructor '
      Console.WriteLine("Object is being created, length = {0}", len)
      length = len
   End Sub
   Public Sub setLength(ByVal len As Double)
      length = len
   End Sub

   Public Function getLength() As Double
      Return length
   End Function
   Shared Sub Main()
      Dim line As Line2 = New Line2(199.0)
      Console.WriteLine("Length of line set by constructor : {0}", line.getLength())
      'set line length '
      line.setLength(68.0)
      Console.WriteLine("Length of line set by setLength : {0}", line.getLength())
      Console.ReadKey()
   End Sub
End Class

執行上面範例程式碼,得到以下結果 -

F:\worksp\vb.net\classes_objects>vbc Line2.vb
Microsoft (R) Visual Basic Compiler version 14.0.1038
for Visual Basic 2012
Copyright (c) Microsoft Corporation.  All rights reserved.
......
F:\worksp\vb.net\classes_objects>Line2.exe
Object is being created, length = 199
Length of line set by constructor : 199
Length of line set by setLength : 68

解構函式是一個類的特殊成員子程式(Sub),只要它的類的一個物件超出了作用域就會被執行。

解構函式名稱為Finalize,它既不能返回值也不能帶任何引數。在關閉檔案,釋放記憶體等程式出來之前,解構函式可以非常有用地釋放資源。

解構函式不能被繼承或過載。

下面的例子演示了如何使用解構函式:

Class Line3
   Private length As Double    ' Length of a line'
   Public Sub New()   'parameterised constructor'
      Console.WriteLine("Object is being created")
   End Sub
   Protected Overrides Sub Finalize()  ' destructor'
      Console.WriteLine("Object is being deleted")
   End Sub
   Public Sub setLength(ByVal len As Double)
      length = len
   End Sub
   Public Function getLength() As Double
      Return length
   End Function
   Shared Sub Main()
      Dim line As Line3 = New Line3()
      'set line length '
      line.setLength(699.0)
      Console.WriteLine("Length of line : {0}", line.getLength())
      Console.ReadKey()
   End Sub
End Class

執行上面範例程式碼,得到以下結果 -

F:\worksp\vb.net\classes_objects>vbc Line3.vb
Microsoft (R) Visual Basic Compiler version 14.0.1038
for Visual Basic 2012
Copyright (c) Microsoft Corporation.  All rights reserved.

......

F:\worksp\vb.net\classes_objects>Line3.exe
Object is being created
Length of line : 699

VB.Net類的共用成員

可以使用Shared關鍵字將類成員定義為靜態的。當將一個類的成員宣告為Shared時,這意味著無論該類建立了多少個物件,該成員只有一個副本。

Shared關鍵字表示一個類只存在一個成員範例。共用變數用於定義常數,因為它們的值可以通過呼叫該類而不建立範例來呼叫獲取。

共用變數可以在成員函式或類定義之外初始化。也可以在類定義中初始化共用變數。

可以宣告一個成員函式為Shared。這樣的函式只能存取共用變數。Shared函式甚至在建立物件之前就存在。

以下範例演示了共用(Shared)成員的使用:

Class StaticVar
   Public Shared num As Integer
   Public Sub count()
      num = num + 100
   End Sub
   Public Shared Function getNum() As Integer
      Return num
   End Function
   Shared Sub Main()
      Dim s As StaticVar = New StaticVar()
      s.count()
      s.count()
      s.count()
      Console.WriteLine("Value of variable num: {0}", StaticVar.getNum())
      Console.ReadKey()
   End Sub
End Class

執行上面範例程式碼,得到以下結果 -

F:\worksp\vb.net\classes_objects>vbc StaticVar.vb
Microsoft (R) Visual Basic Compiler version 14.0.1038
for Visual Basic 2012
Copyright (c) Microsoft Corporation.  All rights reserved.

.....

F:\worksp\vb.net\classes_objects>StaticVar.exe
Value of variable num: 300

繼承

物件導向程式設計中最重要的概念之一就是繼承。繼承允許使用另一個類來定義一個類,這使得建立和維護應用程式變得更容易。這也提供了重用程式碼功能和快速實施時間的機會。

當建立一個類時,程式員可以指定新的類繼承現有類的成員,而不是編寫全新的資料成員和成員函式。這個現有的類被稱為基礎類別,新的類被稱為派生類。

基礎派生類

一個類可以從多個類或介面派生,這意味著它可以從多個基礎類別或介面繼承資料和函式。
VB.Net中用於建立派生類的語法如下所示:

<access-specifier> Class <base_class>
...
End Class
Class <derived_class>: Inherits <base_class>
...
End Class

考慮一個基礎類別Shape及其派生類Rectangle

' 定義基礎類別 '
Class Shape
   Protected width As Integer
   Protected height As Integer
   Public Sub setWidth(ByVal w As Integer)
      width = w
   End Sub
   Public Sub setHeight(ByVal h As Integer)
      height = h
   End Sub
End Class
' 子類或派生類 '
Class Rectangle : Inherits Shape
   Public Function getArea() As Integer
      Return (width * height)
   End Function
End Class
Class RectangleTester
   Shared Sub Main()
      Dim rect As Rectangle = New Rectangle()
      rect.setWidth(15)
      rect.setHeight(25)
      ' Print the area of the object. '
      Console.WriteLine("Total area: {0}", rect.getArea())
      Console.ReadKey()
   End Sub    
End Class

執行上面範例程式碼,得到以下結果 -

F:\worksp\vb.net\classes_objects>vbc BaseDerived.vb
Microsoft (R) Visual Basic Compiler version 14.0.1038
for Visual Basic 2012
Copyright (c) Microsoft Corporation.  All rights reserved.
.....
F:\worksp\vb.net\classes_objects>BaseDerived.exe
Total area: 375

基礎類別初始化

派生類繼承基礎類別成員變數和成員方法。 因此,應該在建立子類之前建立超類物件。 在VB.Net中,超類或基礎類別隱式地被稱為:MyBase

以下程式演示了這一點:


' 定義基礎類別 '
Class Shape
   Protected width As Integer
   Protected height As Integer
   Public Sub setWidth(ByVal w As Integer)
      width = w
   End Sub
   Public Sub setHeight(ByVal h As Integer)
      height = h
   End Sub
End Class
' 子類或派生類 '
Class Rectangle : Inherits Shape
   Public Function getArea() As Integer
      Return (width * height)
   End Function
End Class
Class RectangleTester
   Shared Sub Main()
      Dim rect As Rectangle = New Rectangle()
      rect.setWidth(15)
      rect.setHeight(25)
      ' Print the area of the object. '
      Console.WriteLine("Total area: {0}", rect.getArea())
      Console.ReadKey()
   End Sub    
End Class

執行上面範例程式碼,得到以下結果 -

F:\worksp\vb.net\classes_objects>vbc BaseClassInitialization.vb
Microsoft (R) Visual Basic Compiler version 14.0.1038
for Visual Basic 2012
Copyright (c) Microsoft Corporation.  All rights reserved.
......
F:\worksp\vb.net\classes_objects>BaseClassInitialization.exe
Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5