Option Infer 语句

更新:2007 年 11 月

在变量声明过程中启用局部类型推理。

Option Infer { On | Off }

组成部分

  • On
    可选。启用局部类型推理。

  • Off
    可选。禁用局部类型推理。

说明:

如果没有指定 On 或 Off,则对于在 Visual Basic 2008 中创建的项目,默认值为 On。对于从早期版本升级的项目,默认值为 Off。

备注

如果将 Option Infer 设置为 On,则在声明变量时无需显式声明数据类型。编译器将根据变量的初始化表达式的类型来推断变量的数据类型。例如,当 Option Infer 和 Option Strict 关闭时,声明 Dim someVar = 2 中的变量仅标识为对象。

当 Option Infer 和 Option Strict 为 off 时使用 IntelliSense

声明的 IntelliSense 视图。

当您将 Option Infer 设置为 On 时,编译器会将 someVar 标识为 Integer。

当 Option Infer 为 on 时使用 IntelliSense

声明的 IntelliSense 视图。

然后,编译器就可以检测到项目在使用变量方面存在的不一致情况;否则,可能无法在项目执行前识别出这些不一致的情况。通过将 someVar 标识为 Integer,还使集成开发环境 (IDE) 能够提供完整 IntelliSense 支持。

说明:

如果没有在代码或 IDE 中为 Option Infer 指定值,则对于新创建的项目,编译器的默认值为 Option Infer On。对于升级的项目,默认值为 Option Infer Off。

说明:

对于在以下说明中使用的某些 Visual Studio 用户界面元素,您的计算机可能会显示不同的名称或位置。这些元素取决于您使用的 Visual Studio 版本及设置。有关更多信息,请参见Visual Studio 设置

在文件中设置 Option Infer

  • 在文件顶部任何其他源代码之前键入 Option Infer On 或 Option Infer Off。如果在文件中为 Option Infer 设置的值与 IDE 或命令行中设置的值发生冲突,则文件中的值优先。

在 IDE 中为单个项目设置 Option Infer

  1. 在“解决方案资源管理器”中单击一个项目。

  2. 在“视图”菜单上单击“属性页”,以打开“项目设计器”。

  3. 在“编译”选项卡上的“Option Infer”框中,单击“On”或“Off”。

在 IDE 中设置 Option Infer 的默认值

  1. 在“工具”菜单上单击“选项”。

  2. 展开“项目和解决方案”节点。

  3. 单击“VB 默认值”。

  4. 在“Option Infer”列表中单击“On”或“Off”。

    说明:

    如果使用“工具”菜单设置 Option Infer 的值,则该值将在后续项目中得到保留,直到您对其进行更改。

在命令行中设置 Option Infer

  • /optioninfer 编译器选项包括在 vbc 命令中。

示例

下面的示例演示 Option Infer 语句如何启用局部类型推理。

' Enable Option Infer before trying these examples.

' Variable num is an Integer.
Dim num = 5

' Variable dbl is a Double.
Dim dbl = 4.113

' Variable str is a String.
Dim str = "abc"

' Variable pList is an array of Process objects.
Dim pList = Process.GetProcesses()

' Variable i is an Integer.
For i = 1 To 10
    Console.WriteLine(i)
Next

' If CustomerList is a list of Customer objects,
' variable cust is an instance of the Customer class.
For Each cust In CustomerList
    Console.WriteLine(cust.Name)
Next

' Variable namedCust is an instance of the Customer class.
Dim namedCust = New Customer With {.Name = "Lance Tucker", _
                                   .City = "Seattle"}

' Variable product is an instance of an anonymous type.
Dim product = New With {Key .Name = "paperclips", Key .Price = 1.29}

' If customers is a collection of Customer objects in the following 
' query, the inferred type of cust is Customer, and the inferred type
' of custs is IEnumerable(Of Customer).
Dim custs = From cust In customers _
            Where cust.City = "Seattle" _
            Select cust.Name, cust.ID

请参见

概念

局部类型推理

参考

Dim 语句 (Visual Basic)

Option Compare 语句

Option Explicit 语句 (Visual Basic)

Option Strict 语句

“选项”对话框 ->“项目”->“Visual Basic 默认值”

/optioninfer