HOW TO:呼叫運算子程序 (Visual Basic)How to: Call an Operator Procedure (Visual Basic)

您可以在運算式中使用運算子符號,以呼叫運算子程序。You call an operator procedure by using the operator symbol in an expression. 轉換運算子,在您呼叫CType 函式將值從一種資料類型轉換到另一個。In the case of a conversion operator, you call the CType Function to convert a value from one data type to another.

您未明確呼叫運算子程序。You do not call operator procedures explicitly. 您只使用運算子,或CType函式,在指派陳述式或運算式,您通常會使用運算子相同的方式。You just use the operator, or the CType function, in an assignment statement or an expression, the same way you ordinarily use an operator. Visual Basic 可讓運算子程序的呼叫。Visual Basic makes the call to the operator procedure.

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

若要呼叫運算子程序To call an operator procedure

  1. 在運算式中使用運算子符號,以一般方式。Use the operator symbol in an expression in the ordinary way.

  2. 請確定資料類型的運算元是適用於運算子,且有正確的順序。Be sure the data types of the operands are appropriate for the operator, and in the correct order.

  3. 如預期般,運算子會提供給運算式的值。The operator contributes to the value of the expression as expected.

若要呼叫的轉換運算子程序To call a conversion operator procedure

  1. 使用CType在運算式中。Use CType inside an expression.

  2. 請確定資料類型的運算元會適當轉換,並以正確的順序。Be sure the data types of the operands are appropriate for the conversion, and in the correct order.

  3. CType 呼叫轉換運算子程序,並傳回已轉換的值。CType calls the conversion operator procedure and returns the converted value.

範例Example

下列範例會建立兩個TimeSpan、 將它們相加,並將結果儲存在第三個TimeSpan結構。The following example creates two TimeSpan structures, adds them together, and stores the result in a third TimeSpan structure. TimeSpan結構會定義數個標準運算子的多載的運算子程序。The TimeSpan structure defines operator procedures to overload several standard operators.

Dim firstSpan As New TimeSpan(3, 30, 0)
Dim secondSpan As New TimeSpan(1, 30, 30)
Dim combinedSpan As TimeSpan = firstSpan + secondSpan
Dim s As String = firstSpan.ToString() & 
          " + " & secondSpan.ToString() & 
          " = " & combinedSpan.ToString()
MsgBox(s)

因為TimeSpan多載標準+運算子,前一個範例會呼叫運算子程序計算的值時combinedSpanBecause TimeSpan overloads the standard + operator, the previous example calls an operator procedure when it calculates the value of combinedSpan.

如需呼叫交談運算子程序的範例,請參閱How to:使用定義運算子的類別For an example of calling a conversation operator procedure, see How to: Use a Class that Defines Operators.

編譯程式碼Compiling the Code

請務必在類別或您使用的結構會定義您想要使用的運算子。Be sure the class or structure you are using defines the operator you want to use.

另請參閱See also