# 運算子程序 (Visual Basic)Operator Procedures (Visual Basic)

## 定義運算子程式的時機When to Define Operator Procedures

Visual Basic 只會定義其基本資料類型的運算子。Visual Basic defines operators only on its fundamental data types. 當一或兩個運算元屬於您的類別或結構類型時，您可以定義運算子的行為。You can define the behavior of an operator when one or both of the operands are of the type of your class or structure.

## 運算子程式的類型Types of Operator Procedure

• 一元運算子的定義，其中引數是您的類別或結構的類型。A definition of a unary operator where the argument is of the type of your class or structure.

• 二元運算子的定義，其中至少有一個引數屬於您的類別或結構的類型。A definition of a binary operator where at least one of the arguments is of the type of your class or structure.

• 轉換運算子的定義，其中的引數是您的類別或結構的類型。A definition of a conversion operator where the argument is of the type of your class or structure.

• 轉換運算子的定義，可傳回您的類別或結構的類型。A definition of a conversion operator that returns the type of your class or structure.

## 宣告語法Declaration Syntax

Public Shared [Widening | Narrowing] Operator operatorsymbol ( operand1 [,  operand2 ]) As datatype

' Statements of the operator procedure.

End Operator


## 呼叫語法Calling Syntax

Dim testStruct As 結構名稱Dim testStruct As structurename

Dim testNewStruct As 結構名稱 = testStruct 運算子符號 10Dim testNewStruct As structurename = testStruct operatorsymbol 10

### 宣告和呼叫的圖例Illustration of Declaration and Call

Public Structure veryLong
Dim highOrder As Long
Dim lowOrder As Long
Public Shared Operator +(ByVal v As veryLong,
ByVal w As veryLong) As veryLong
Dim sum As New veryLong
sum = v
Try
sum.lowOrder += w.lowOrder
Catch ex As System.OverflowException
sum.lowOrder -= (Long.MaxValue - w.lowOrder + 1)
sum.highOrder += 1
End Try
sum.highOrder += w.highOrder
Return sum
End Operator
End Structure


Dim v1, v2, v3 As veryLong
v1.highOrder = 1
v1.lowOrder = Long.MaxValue
v2.highOrder = 0
v2.lowOrder = 4
v3 = v1 + v2