HOW TO:使用一個類別來定義運算子 (Visual Basic)How to: Use a Class that Defines Operators (Visual Basic)

如果您使用的類別或結構,定義自己的運算子,您可以從 Visual Basic 中存取這些運算子。If you are using a class or structure that defines its own operators, you can access those operators from Visual Basic.

類別或結構上定義的運算子,也稱為多載運算子。Defining an operator on a class or structure is also called overloading the operator.


下列範例會存取 SQL 結構SqlString,其定義轉換運算子 (CType 函式) 中的 SQL 字串和 Visual Basic 字串之間的兩個方向。The following example accesses the SQL structure SqlString, which defines the conversion operators (CType Function) in both directions between a SQL string and a Visual Basic string. 使用CType( SQL 字串運算式String)將 SQL 字串轉換成 Visual Basic 字串,並CType( Visual Basic 字串運算式SqlString )另一個方向的轉換。Use CType(SQL string expression, String) to convert a SQL string to a Visual Basic string, and CType(Visual Basic string expression, SqlString) to convert in the other direction.

' Insert the following line at the beginning of your source file.
Imports System.Data.SqlTypes
Public Sub setJobString(ByVal g As Integer)
    Dim title As String
    Dim jobTitle As System.Data.SqlTypes.SqlString
    Select Case g
        Case 1
            title = "President"
        Case 2
            title = "Vice President"
        Case 3
            title = "Director"
        Case 4
            title = "Manager"
        Case Else
            title = "Worker"
    End Select
    jobTitle = CType(title, SqlString)
    MsgBox("Group " & CStr(g) & " generates title """ &
          CType(jobTitle, String) & """")
End Sub

SqlString結構會定義轉換運算子 (CType 函式) 從StringSqlString,從另一種SqlStringStringThe SqlString structure defines a conversion operator (CType Function) from String to SqlString and another from SqlString to String. 指派的陳述式titlejobTitle會使用第一個運算子,而MsgBox函式呼叫會使用第二個。The statement that assigns title to jobTitle makes use of the first operator, and the MsgBox function call uses the second.

編譯程式碼Compiling the Code

請務必在類別或您使用的結構會定義您想要使用的運算子。Be sure the class or structure you are using defines the operator you want to use. 請勿假設類別或結構定義每個適用於多載的運算子。Do not assume that the class or structure has defined every operator available for overloading. 如需可用的運算子,請參閱Operator StatementFor a list of available operators, see Operator Statement.

包含適當Imports原始程式檔的 SQL 字串開頭的陳述式 (在此情況下System.Data.SqlTypes)。Include the appropriate Imports statement for the SQL string at the beginning of your source file (in this case System.Data.SqlTypes).

您的專案必須參考 System.Data 和 System.XML。Your project must have references to System.Data and System.XML.

另請參閱See also