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.

Option Strict Off对于所有三个条件,语句将关闭错误和警告检查,即使关联的 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. Option Strict On即使关联的 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 启用了也是如此。So these conversions do not generate an implicit narrowing conversion error, even if Option Strict is on.

如果调用的方法具有的数据类型与相应的参数不同,则收缩转换将在打开时导致编译时错误 Option StrictWhen 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 StrictThis occurs even if Option Strict is on. 有关详细信息,请参阅中的 "收缩转换" 一节 。下一语句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

如果无法为已声明的变量推断出合适的类型,则会发生隐式对象类型错误,因此 Object 类型是推断出来的。Implicit object type errors occur when an appropriate type cannot be inferred for a declared variable, so a type of Object is inferred. 这主要是在未使用 As 子句的情况下使用 Dim 语句声明变量,且 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. 有关详细信息,请参阅 选项推断语句Visual Basic 语言规范For more information, see Option Infer Statement and the Visual Basic Language Specification.

对于方法参数, As 如果为 off,则子句是可选的 Option StrictFor 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 InferNo compile-time error occurs in this case when Option Strict is on and Option Infer is on. 这是一个示例 Dim something = NothingAn 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 InferOption 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 StrictIf 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. 有关详细信息,请参阅个性化设置 IDEFor more information, see Personalizing the IDE.

  1. 解决方案资源管理器中,选择一个项目。In Solution Explorer, select a project. “项目” 菜单上,单击 “属性”On the Project menu, click Properties.

  2. 在 " 编译 " 选项卡上,在 " 选项严格限制 " 框中设置值。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 StrictThe 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

  • 隐式类型;假定为对象****Implicit type; object assumed

“Option Strict”设置为“开启”时,所有这三个警告配置设置都将被设置为“错误”************。When you set Option Strict to On, all three of these warning configuration settings are set to Error. “Option Strict”设置为“关闭”时,所有这三个设置都将被设置为“无”************。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.

为新项目设置选项 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

下面的示例演示由使用隐式类型声明的变量导致的错误 ObjectThe 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