IsTrue 運算子 (Visual Basic)IsTrue Operator (Visual Basic)

判斷運算式是否為TrueDetermines whether an expression is True.

您無法在IsTrue程式碼中明確呼叫, 但是 Visual Basic 編譯器可以使用它來產生來自子句OrElse的程式碼。You cannot call IsTrue explicitly in your code, but the Visual Basic compiler can use it to generate code from OrElse clauses. 如果您定義了類別或結構, 然後在OrElse子句中使用該類型的變數, 您必須在該類別或結構上定義。 IsTrueIf you define a class or structure and then use a variable of that type in an OrElse clause, you must define IsTrue on that class or structure.

編譯器會將IsTrueIsFalse運算子視為相符的配對The compiler considers the IsTrue and IsFalse operators as a matched pair. 這表示如果您定義其中一個, 則也必須定義另一個。This means that if you define one of them, you must also define the other one.

編譯器使用 IsTrueCompiler Use of IsTrue

當您定義了類別或結構時, 可以在ForIfElse IfWhile語句中, 或在When子句中使用該類型的變數。When you have defined a class or structure, you can use a variable of that type in a For, If, Else If, or While statement, or in a When clause. 如果您這樣做, 編譯器需要一個運算子, 將您的型別轉換Boolean成值, 讓它可以測試條件。If you do this, the compiler requires an operator that converts your type into a Boolean value so it can test a condition. 它會依下列順序搜尋適合的運算子:It searches for a suitable operator in the following order:

  1. 從您的類別或結構到Boolean的擴輾轉換運算子。A widening conversion operator from your class or structure to Boolean.

  2. 從您的類別或結構到Boolean?的擴輾轉換運算子。A widening conversion operator from your class or structure to Boolean?.

  3. 類別IsTrue或結構上的運算子。The IsTrue operator on your class or structure.

  4. 的縮小轉換Boolean?不牽涉到從Boolean轉換成Boolean?的。A narrowing conversion to Boolean? that does not involve a conversion from Boolean to Boolean?.

  5. 從您的類別或結構到Boolean的縮小轉換運算子。A narrowing conversion operator from your class or structure to Boolean.

如果您尚未定義任何對Boolean IsTrue或運算子的轉換, 則編譯器會發出錯誤信號。If you have not defined any conversion to Boolean or an IsTrue operator, the compiler signals an error.

注意

運算子可以多載, 這表示當類別或結構的運算元具有該類別或結構的類型時, 可以重新定義其行為。 IsTrueThe IsTrue operator can be overloaded, which means that a class or structure can redefine its behavior when its operand has the type of that class or structure. 如果您的程式碼在這類類別或結構上使用這個運算子, 請務必瞭解其已重新定義的行為。If your code uses this operator on such a class or structure, be sure you understand its redefined behavior. 如需詳細資訊,請參閱 Operator ProceduresFor more information, see Operator Procedures.

範例Example

下列程式碼範例會定義包含IsFalseIsTrue運算子之定義的結構外框。The following code example defines the outline of a structure that includes definitions for the IsFalse and IsTrue operators.

Public Structure p
    Dim a As Double
    Public Shared Operator IsFalse(ByVal w As p) As Boolean
        Dim b As Boolean
        ' Insert code to calculate IsFalse of w.
        Return b
    End Operator
    Public Shared Operator IsTrue(ByVal w As p) As Boolean
        Dim b As Boolean
        ' Insert code to calculate IsTrue of w.
        Return b
    End Operator
End Structure

另請參閱See also