Visual Basic 中的元件
以下是簡單字串元件的完整原始程式碼清單在 Visual Basic 中的樣子:
清單 1:Visual Basic 中的元件 (CompVB.vb)
Option Explicit
Option Strict
Imports System
Namespace CompVB
Public Class StringComponent
Private StringSet(3) As String
Public Sub New()
MyBase.New
StringSet(0) = "Visual Basic String 0"
StringSet(1) = "Visual Basic String 1"
StringSet(2) = "Visual Basic String 2"
StringSet(3) = "Visual Basic String 3"
End Sub
Public Function GetString(ByVal index as Integer)
As String
If ((index < 0) or (index >= Count)) then
throw new IndexOutOfRangeException
End If
GetString = StringSet(index)
End Function
ReadOnly Property Count() As Long
Get
Count = StringSet.Length
End Get
End Property
End Class
End Namespace
與 Managed Extensions for C++ 和 Visual C# 一樣,命名空間和類別名稱都要用程式碼加以指定。
這個程式碼還引用了新的 Option Strict 陳述式,它會控制變數型別轉換為明確或隱含。進行隱含轉換時不需要任何特殊語法,但是,進行明確轉換時則必須使用轉換運算子。如果開啟這個選項,只有擴展轉換 (例如從 Integer 轉換成 Double) 可用隱含方式進行。在編譯期間,也可以使用 /optionstrict+ 編譯器參數來啟動 Option Strict 函式。
在 Visual Basic 中,為類別建構函式指定的名稱為 New,而非其他語言中所使用的類別名稱。由於建構函式不會傳回值,因此,在 Visual Basic 中是實做為 Sub,而非 Function:
Public Sub New()
...
End Sub
也請注意下面這個陳述式:
MyBase.New
這個必要的陳述式會呼叫基底類別建構函式。在 C++ 和 Managed Extensions for C# 中,基底類別建構函式呼叫是由編譯器自動產生。
以下是 GetString 方法,它會使用整數引數並傳回字串 (在 Visual Basic 中,傳回值的副程式稱為函式):
Public Function GetString(ByVal index as Integer)
As String
If ((index < 0) or (index >= Count)) then
throw new IndexOutOfRangeException
End If
GetString = StringSet(index)
End Function
GetString 方法中的 throw 陳述式會將新的 Runtime 例外處理反白顯示:
throw new IndexOutOfRangeException
這個陳述式會建立並擲回 IndexOutOfRangeException 型別的新物件。
**注意 **先前版本的 Visual Basic Runtime 是實做為 Err。
最後,您會建立唯讀的 Count 屬性:
ReadOnly Property Count() As Long
Get
Count = StringSet.Length
End Get
End Property
從命令列建置非常簡單。唯一的變更是要將元件寫入相關的 ..\Bin 子目錄中,如以下所示:
vbc.exe /t:library /debug+ /optionstrict+ /out:..\bin\CompVB.dll CompVB.vb