Option Strict StatementOption Strict Statement

將隱含資料類型轉換限制為僅限擴輾轉換、不允許晚期繫結,而且不允許導致 Object 類型的隱含類型。Restricts implicit data type conversions to only widening conversions, disallows late binding, and disallows implicit typing that results in an Object type.

語法Syntax

Option Strict { On | Off }  

組件Parts

詞彙Term 定義Definition
On 選擇項。Optional. 啟用 Option Strict 檢查。Enables Option Strict checking.
Off 選擇項。Optional. 停用 Option Strict 檢查。Disables Option Strict checking.

備註Remarks

Option Strict OnOption Strict 出現在檔案中時,下列情況會導致編譯時期錯誤:When Option Strict On or Option Strict appears in a file, the following conditions cause a compile-time error:

  • 隱含縮小轉換Implicit narrowing conversions

  • 晚期繫結Late binding

  • 導致 Object 類型的隱含類型化Implicit typing that results in an Object type

注意

在 [[編譯] 頁面上,專案設計工具] ([Visual Basic])可設定的警告設定中,有三個設定會對應到造成編譯時期錯誤的三個條件。In the warning configurations that you can set on the Compile Page, Project Designer (Visual Basic), there are three settings that correspond to the three conditions that cause a compile-time error. 如需有關如何使用這些設定的詳細資訊,請參閱本主題稍後的在 IDE 中設定警告設定For information about how to use these settings, see To set warning configurations in the IDE later in this topic.

@No__t_0 語句會關閉所有三個條件的錯誤和警告檢查,即使相關聯的 IDE 設定指定要開啟這些錯誤或警告。The Option Strict Off statement turns off error and warning checking for all three conditions, even if the associated IDE settings specify to turn on these errors or warnings. @No__t_0 語句會針對這三個條件開啟錯誤和警告檢查,即使相關聯的 IDE 設定指定要關閉這些錯誤或警告。The Option Strict On statement turns on error and warning checking for all three conditions, even if the associated IDE settings specify to turn off these errors or warnings.

如果使用的話,Option Strict 語句必須出現在檔案中的任何其他程式碼語句之前。If used, the Option Strict statement must appear before any other code statements in a file.

當您將 Option Strict 設定為 On 時,Visual Basic 會檢查是否已針對所有程式設計項目指定資料類型。When you set Option Strict to On, Visual Basic checks that data types are specified for all programming elements. 您可以明確指定資料類型,或使用區欄位型別推斷來指定。Data types can be specified explicitly, or specified by using local type inference. 建議您為所有的程式設計項目指定資料類型,原因如下:Specifying data types for all your programming elements is recommended, for the following reasons:

  • 它會針對您的變數和參數啟用 IntelliSense 支援。It enables IntelliSense support for your variables and parameters. 這可讓您在輸入程式碼時看到其屬性和其他成員。This enables you to see their properties and other members as you type code.

  • 它可讓編譯器執行類型檢查。It enables the compiler to perform type checking. 類型檢查可協助您尋找在執行時間因類型轉換錯誤而失敗的語句。Type checking helps you find statements that can fail at run time because of type conversion errors. 它也會識別不支援這些方法之物件上方法的呼叫。It also identifies calls to methods on objects that do not support those methods.

  • 它會加速程式碼的執行。It speeds up the execution of code. 其中一個原因是,如果您未指定程式設計項目的資料類型,Visual Basic 編譯器會為它指派 Object 類型。One reason for this is that if you do not specify a data type for a programming element, the Visual Basic compiler assigns it the Object type. 已編譯的程式碼可能必須在 Object 和其他資料類型之間來回轉換,這樣會降低效能。Compiled code might have to convert back and forth between Object and other data types, which reduces performance.

隱含縮小轉換錯誤Implicit Narrowing Conversion Errors

隱含資料類型轉換是縮小轉換時,會發生隱含縮小轉換錯誤。Implicit narrowing conversion errors occur when there is an implicit data type conversion that is a narrowing conversion.

Visual Basic 可以將許多資料類型轉換成其他資料類型。Visual Basic can convert many data types to other data types. 當某個資料類型的值轉換成具有較少精確度或較小容量的資料類型時,可能會發生資料遺失。Data loss can occur when the value of one data type is converted to a data type that has less precision or a smaller capacity. 如果這類縮小轉換失敗,就會發生執行階段錯誤。A run-time error occurs if such a narrowing conversion fails. Option Strict 可確保這些縮小轉換的編譯時間通知,讓您可以避免它們。Option Strict ensures compile-time notification of these narrowing conversions so that you can avoid them. 如需詳細資訊,請參閱隱含和明確轉換擴展和縮小轉換For more information, see Implicit and Explicit Conversions and Widening and Narrowing Conversions.

可能造成錯誤的轉換包括運算式中發生的隱含轉換。Conversions that can cause errors include implicit conversions that occur in expressions. 如需詳細資訊,請參閱下列主題:For more information, see the following topics:

當您使用& 運算子來串連字號串時,會將字串的所有轉換視為擴展。When you concatenate strings by using the & Operator, all conversions to the strings are considered to be widening. 因此,即使 Option Strict 是 on,這些轉換也不會產生隱含的縮小轉換錯誤。So these conversions do not generate an implicit narrowing conversion error, even if Option Strict is on.

當您呼叫的方法具有與對應參數不同的資料類型引數時,如果 Option Strict 是 on,則縮小轉換會導致編譯時期錯誤。When you call a method that has an argument that has a data type different from the corresponding parameter, a narrowing conversion causes a compile-time error if Option Strict is on. 您可以使用擴輾轉換或明確轉換來避免編譯時期錯誤。You can avoid the compile-time error by using a widening conversion or an explicit conversion.

在編譯時間會抑制隱含縮小轉換錯誤,以從 For Each…Next 集合中的元素轉換為迴圈控制變數。Implicit narrowing conversion errors are suppressed at compile-time for conversions from the elements in a For Each…Next collection to the loop control variable. 即使 Option Strict 是 on,也會發生這種情況。This occurs even if Option Strict is on. 如需詳細資訊,請參閱For Each ... 中的「縮小轉換」一節。下一個語句For more information, see the "Narrowing Conversions" section in For Each...Next Statement.

晚期繫結錯誤Late Binding Errors

當物件指派給宣告為 Object 類型之變數的屬性或方法時,該物件即為「晚期繫結」。An object is late bound when it is assigned to a property or method of a variable that is declared to be of type Object. 如需詳細資訊,請參閱早期和晚期繫結For more information, see Early and Late Binding.

隱含物件類型錯誤Implicit Object Type Errors

無法推斷宣告變數的適當類型時,會發生隱含物件類型錯誤,因此推斷類型為 ObjectImplicit object type errors occur when an appropriate type cannot be inferred for a declared variable, so a type of Object is inferred. 這主要是發生在您使用 Dim 陳述式宣告變數而未使用 As 子句,並且 Option Infer 已設為關閉的時候。This primarily occurs when you use a Dim statement to declare a variable without using an As clause, and Option Infer is off. 如需詳細資訊,請參閱Option 推斷語句Visual Basic 語言規格For more information, see Option Infer Statement and the Visual Basic Language Specification.

對於方法參數而言,如果 Option Strict 為 off,As 子句是選擇性的。For method parameters, the As clause is optional if Option Strict is off. 不過,如果有任何一個參數使用 As 子句,則它們都必須使用它。However, if any one parameter uses an As clause, they all must use it. 如果 Option Strict 是 on,則每個參數定義都需要 As 子句。If Option Strict is on, the As clause is required for every parameter definition.

如果您在未使用 As 子句的情況下宣告變數,並將它設定為 Nothing,則變數的類型會是 ObjectIf you declare a variable without using an As clause and set it to Nothing, the variable has a type of Object. Option Strict 是 on,且 Option Infer 為 on 時,就不會發生編譯時期錯誤。No compile-time error occurs in this case when Option Strict is on and Option Infer is on. @No__t_0 的範例。An example of this is Dim something = Nothing.

預設資料類型和值Default Data Types and Values

下表描述在Dim 語句中指定資料類型和初始化運算式的各種組合結果。The following table describes the results of various combinations of specifying the data type and initializer in a Dim Statement.

指定了資料類型?Data type specified? 指定了初始設定式?Initializer specified? 範例Example 結果Result
No No Dim qty 如果 Option Strict 已關閉 (預設值),此變數會設定為 NothingIf Option Strict is off (the default), the variable is set to Nothing.

如果 Option Strict 已開啟,就會發生編譯時間錯誤。If Option Strict is on, a compile-time error occurs.
No [是]Yes Dim qty = 5 如果 Option Infer 已開啟 (預設值),此變數會採用初始設定式的資料類型。If Option Infer is on (the default), the variable takes the data type of the initializer. 請參閱區欄位型別推斷See Local Type Inference.

如果 Option Infer 已關閉,且 Option Strict 也已關閉,此變數會採用 Object 的資料類型。If Option Infer is off and Option Strict is off, the variable takes the data type of Object.

如果 Option Infer 已關閉,但是 Option Strict 已開啟,就會發生編譯時間錯誤。If Option Infer is off and Option Strict is on, a compile-time error occurs.
[是]Yes No Dim qty As Integer 變數會初始化為資料類型的預設值。The variable is initialized to the default value for the data type. 如需詳細資訊,請參閱Dim 語句For more information, see Dim Statement.
[是]Yes [是]Yes Dim qty As Integer = 5 如果初始設定式的資料類型無法轉換成指定的資料類型,就會發生編譯時期錯誤。If the data type of the initializer is not convertible to the specified data type, a compile-time error occurs.

當 Option Strict 語句不存在時When an Option Strict Statement Is Not Present

如果原始程式碼不包含 Option Strict 語句,則會使用 [編譯] 頁面上的 [ Option strict ] 設定([專案設計工具] (Visual Basic))If the source code does not contain an Option Strict statement, the Option strict setting on the Compile Page, Project Designer (Visual Basic) is used. [編譯] 頁面有一些設定,可對產生錯誤的條件提供額外的控制。The Compile Page has settings that provide additional control over the conditions that generate an error.

如果您使用命令列編譯器,您可以使用-optionstrict編譯器選項來指定 Option Strict 的設定。If you are using the command-line compiler, you can use the -optionstrict compiler option to specify a setting for Option Strict.

若要在 IDE 中設定 Option StrictTo set Option Strict in the IDE

注意

在下列指示的某些 Visual Studio 使用者介面項目中,您的電腦可能會顯示不同的名稱或位置:Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. 您所擁有的 Visual Studio 版本以及使用的設定會決定這些項目。The Visual Studio edition that you have and the settings that you use determine these elements. 如需詳細資訊,請參閱將 Visual Studio IDE 個人化For more information, see Personalizing the IDE.

  1. 在方案總管中選取專案。In Solution Explorer, select a project. 在 [專案] 功能表上,按一下 [屬性]。On the Project menu, click Properties.

  2. 在 [編譯] 索引標籤上,于 [選項 Strict ] 方塊中設定值。On the Compile tab, set the value in the Option Strict box.

若要在 IDE 中設定警告設定To set warning configurations in the IDE

當您使用 [編譯] 頁面([專案設計工具] (Visual Basic),而不是 Option Strict 語句時,您可以對產生錯誤的條件進行額外的控制。When you use the Compile Page, Project Designer (Visual Basic) instead of an Option Strict statement, you have additional control over the conditions that generate errors. [編譯] 頁面的 [警告設定] 區段中,具有對應于在 Option Strict 為 on 時造成編譯時期錯誤的三個條件。The Warning configurations section of the Compile Page has settings that correspond to the three conditions that cause a compile-time error when Option Strict is on. 以下是這些設定:Following are these settings:

  • 隱含轉換Implicit conversion

  • 晚期繫結,執行階段時呼叫可能失敗Late binding; call could fail at run time

  • 隱含類型,假設是 ObjectImplicit type; object assumed

當您將 [Option Strict] 設定為 [On] 時,這三個警告組態設定都會設定為 [錯誤]。When you set Option Strict to On, all three of these warning configuration settings are set to Error. 當您將 [Option Strict] 設定為 [Off] 時,所有三個設定都會設定為 [無]。When you set Option Strict to Off, all three settings are set to None.

您可以將每個警告組態個別變更為 [無]、[警告] 或 [錯誤]。You can individually change each warning configuration setting to None, Warning, or Error. 如果三個警告組態設定皆設為 [錯誤],On 會出現在 Option strict 方塊中。If all three warning configuration settings are set to Error, On appears in the Option strict box. 如果這三個都設定為 [無],Off 會出現在此方塊中。If all three are set to None, Off appears in this box. 若為這些設定的其他任何組合,則會出現 [(自訂)]。For any other combination of these settings, (custom) appears.

設定新專案的 Option Strict 預設設定To set the Option Strict default setting for new projects

當您建立專案時,[編譯] 索引標籤上的 [ option strict ] 設定會設定為 [選項] 對話方塊中的 [ option strict ] 設定。When you create a project, the Option Strict setting on the Compile tab is set to the Option Strict setting in the Options dialog box.

若要在此對話方塊中設定 Option Strict,請在 [工具] 功能表上按一下 [選項]。To set Option Strict in this dialog box, on the Tools menu, click Options. 在 [選項] 對話方塊中,展開 [專案和方案],然後按一下 [VB 預設值]。In the Options dialog box, expand Projects and Solutions, and then click VB Defaults. VB 預設值中的初始預設設定是 OffThe initial default setting in VB Defaults is Off.

若要在命令列上設定 Option StrictTo set Option Strict on the command line

vbc命令中包含-optionstrict編譯器選項。Include the -optionstrict compiler option in the vbc command.

範例Example

下列範例示範以縮小轉換的隱含類型轉換所造成的編譯時期錯誤。The following examples demonstrate compile-time errors caused by implicit type conversions that are narrowing conversions. 這個錯誤類別會對應至 [編譯] 頁面上的隱含轉換條件。This category of errors corresponds to the Implicit conversion condition on the Compile Page.

' If Option Strict is on, this implicit narrowing
' conversion causes a compile-time error.
' The commented statements below use explicit
' conversions to avoid a compile-time error.
Dim cyclists As Long = 5
Dim bicycles As Integer = cyclists
'Dim bicycles As Integer = CType(cyclists, Integer)
'Dim bicycles As Integer = CInt(cyclists)
'Dim bicycles As Integer = Convert.ToInt32(cyclists)


' If Option Strict is on, this implicit narrowing
' conversion causes a compile-time error.
' The commented statements below use explicit
' conversions to avoid a compile-time error.
Dim charVal As Char = "a"
'Dim charVal As Char = "a"c
'Dim charVal As Char = CType("a", Char)


' If Option Strict is on, a compile-time error occurs.
' If Option Strict is off, the string is implicitly converted
' to a Double, and then is added to the other number.
Dim myAge As Integer = "34" + 6


' If Option Strict is on, a compile-time error occurs.
' If Option Strict is off, the floating-point number
' is implicitly converted to a Long.
Dim num = 123.45 \ 10

範例Example

下列範例示範晚期繫結所造成的編譯時期錯誤。The following example demonstrates a compile-time error caused by late binding. 這個錯誤類別會對應至晚期繫結; 在 [編譯] 頁面上,[呼叫可能會在執行時間失敗] 條件。This category of errors corresponds to the Late binding; call could fail at run time condition on the Compile Page.

' If Option Strict is on, this late binding
' causes a compile-time error. If Option Strict
' is off, the late binding instead causes a
' run-time error.
Dim punchCard As New Object
punchCard.Column = 5

範例Example

下列範例示範以隱含類型的 Object 宣告的變數所造成的錯誤。The following examples demonstrate errors caused by variables that are declared with an implicit type of Object. 這個類別的錯誤對應于隱含類型; 在 [編譯] 頁面上的 [物件假設] 條件。This category of errors corresponds to the Implicit type; object assumed condition on the Compile Page.

' If Option Strict is on and Option Infer is off,
' this Dim statement without an As clause 
' causes a compile-time error.
Dim cardReaders = 5

' If Option Strict is on, a compile-time error occurs.
' If Option Strict is off, the variable is set to Nothing.
Dim dryWall
' If Option Strict is on, this parameter without an
' As clause causes a compile-time error.
Private Sub DetectIntergalacticRange(ByVal photonAttenuation)

End Sub

請參閱See also