DirectCast 運算子 (Visual Basic)

根據繼承或實作引進類型轉換作業。

備註

DirectCast 不會使用 Visual Basic 執行階段協助程式常式進行轉換,因此可提供比 CType 在資料類型 Object 之間來回轉換時更好的效能。

DirectCast 關鍵字的使用方式與使用 CType 函式TryCast 運算子關鍵字的方式類似。 您會提供運算式作為第一個引數,並提供要轉換的類型作為第二個引數。 DirectCast 要求兩個引數的資料類型之間有繼承或實作關係。 這表示其中一種類型必須繼承自或實作另一種類型。

錯誤和失敗

如果偵測到沒有繼承或實作關係存在,則 DirectCast 會產生編譯器錯誤。 但沒有編譯器錯誤並不保證轉換成功。 如果所需的轉換為縮小轉換,則在執行階段可能會失敗。 如果發生這種情況,則執行階段會擲回 InvalidCastException 錯誤。

轉換關鍵字

類型轉換關鍵字的比較如下所示。

關鍵字 資料類型 引數關係 執行階段失敗
CType Function 任何資料類型 必須在兩種資料類型之間定義放大或縮小轉換 擲回 InvalidCastException
DirectCast 任何資料類型 一種類型必須繼承自或實作另一種類型 擲回 InvalidCastException
TryCast 運算子 僅限參考型別 一種類型必須繼承自或實作另一種類型 傳回 Nothing

範例

下列範例示範 DirectCast 的兩個用法,一個在執行階段失敗,一個成功。

Dim q As Object = 2.37
Dim i As Integer = CType(q, Integer)
' The following conversion fails at run time
Dim j As Integer = DirectCast(q, Integer)
Dim f As New System.Windows.Forms.Form
Dim c As System.Windows.Forms.Control
' The following conversion succeeds.
c = DirectCast(f, System.Windows.Forms.Control)

在上述範例中,q 的執行階段類型為 DoubleCType 成功,因為 Double 可以轉換為 Integer。 不過,第一個 DirectCast 在執行階段失敗,因為 Double 的執行階段類型與 Integer 之間沒有繼承關聯性,即使轉換存在也一樣。 第二個 DirectCast 則成功,因為它從類型 Form 轉換成類型 Control,其繼承來源為 Form

另請參閱