为什么 Option Explicit 仍然允许 Visual Studio 中的隐式 For 循环?
Why does Option Explicit still allow implicit For loops in Visual Studio?
考虑以下代码:
Sub Foo()
For i = 0 To 100
'Do stuff
Next
End Sub
当我打开 Option Explicit
ON 时,编译应该会失败,因为 i
没有明确声明。事实上,当我使用 VBCodeProvider
编译此类代码时,它会失败并显示正确的错误
(BC30451): "i" is not declared. It may be inaccessible due to its protection level.
这是预期的行为。
但是,当我在 Visual Studio 项目中使用这段代码时,无论我如何设置 Option Explicit
,它都能正常编译。我是否在项目设置或代码文件中启用该选项并不重要。
这似乎只有在 For
循环计数器变量中才会出现这种情况。对于其他情况,例如
Sub Foo()
Stuff = 3
End Sub
它也会在 Visual Studio 中抛出一个编译时错误。所以 Option Explicit
有效,但似乎被 For
计数器忽略。
这怎么可能?我找不到任何关于此的信息,我想知道是否还有其他类似的案例。这是我养成的一个坏习惯,隐含地编写 For 计数器,它总是被 Visual Studio 默默地忽略——我认为这是不好的。
我使用的是 Visual Studio 2015,但以前的版本也是如此。
这是允许的,因为这是 VB.NET 中设计 For
循环的方式。
documentation explains it all, especially the optional Counter
-argument:
Is datatype present? Is counter already defined? Result
(whether counter
defines a new local variable
that’s scoped to the entire For...Next loop)
......
No No Yes. The data type is inferred
from the start, end, and step expressions.
For information about type inference,
see Option Infer Statement and Local Type Inference (Visual Basic).
......
你的例子:
For i = 0 To 100
'Do stuff
Next
类型是从反驳论据中推断出来的。由于 0
和 100
是整数,因此类型是 System.Int32
.
值得一提的是,这与您在声明变量时用于 enable/disable 局部类型推断的 Option Infer
语句有关。但是即使您禁用类型推断,for 循环也会以这种方式工作。
不要将 option infer on
与 option explicit off
混淆,与使用明确声明的相同类型编写的代码相比,在性能或类型安全方面没有差异。
Option Infer Statement and Local Type Inference (Visual Basic).
考虑以下代码:
Sub Foo()
For i = 0 To 100
'Do stuff
Next
End Sub
当我打开 Option Explicit
ON 时,编译应该会失败,因为 i
没有明确声明。事实上,当我使用 VBCodeProvider
编译此类代码时,它会失败并显示正确的错误
(BC30451): "i" is not declared. It may be inaccessible due to its protection level.
这是预期的行为。
但是,当我在 Visual Studio 项目中使用这段代码时,无论我如何设置 Option Explicit
,它都能正常编译。我是否在项目设置或代码文件中启用该选项并不重要。
这似乎只有在 For
循环计数器变量中才会出现这种情况。对于其他情况,例如
Sub Foo()
Stuff = 3
End Sub
它也会在 Visual Studio 中抛出一个编译时错误。所以 Option Explicit
有效,但似乎被 For
计数器忽略。
这怎么可能?我找不到任何关于此的信息,我想知道是否还有其他类似的案例。这是我养成的一个坏习惯,隐含地编写 For 计数器,它总是被 Visual Studio 默默地忽略——我认为这是不好的。
我使用的是 Visual Studio 2015,但以前的版本也是如此。
这是允许的,因为这是 VB.NET 中设计 For
循环的方式。
documentation explains it all, especially the optional Counter
-argument:
Is datatype present? Is counter already defined? Result
(whether counter
defines a new local variable
that’s scoped to the entire For...Next loop)
......
No No Yes. The data type is inferred
from the start, end, and step expressions.
For information about type inference,
see Option Infer Statement and Local Type Inference (Visual Basic).
......
你的例子:
For i = 0 To 100
'Do stuff
Next
类型是从反驳论据中推断出来的。由于 0
和 100
是整数,因此类型是 System.Int32
.
值得一提的是,这与您在声明变量时用于 enable/disable 局部类型推断的 Option Infer
语句有关。但是即使您禁用类型推断,for 循环也会以这种方式工作。
不要将 option infer on
与 option explicit off
混淆,与使用明确声明的相同类型编写的代码相比,在性能或类型安全方面没有差异。
Option Infer Statement and Local Type Inference (Visual Basic).