【发布时间】:2014-10-02 19:38:28
【问题描述】:
这是我从这段简单的代码中得到的特殊结果。
假设您想创建一个字符串类型的变量,而不将其声明为字符串。您可以这样做并且不会从编译器中得到任何错误:
Option Strict On
' Produces no errors:
Dim MyString = "Random String"
您也可以这样做并且不会出现任何错误:
Option Infer Off
' Produce no errors as well.
Dim MyString = "Random String"
但是,当你同时结合 Option String On 和 Option Infer Off 时,会出现错误:
Option Strict On
Option Infer Off
' The following line generates an error -
' Option Strict On requires all variable declarations to have an "As" clause
Dim MyString = "Random String"
为什么Option Strict需要和Option Infer结合?特别是当错误明确指出以下错误是“Option Strict”类型时。为什么不能单独 Option Strict 发现该行是错误的?
【问题讨论】:
-
见http://msdn.microsoft.com/de-de/library/bb384665.aspx。有一个表格列出了这些声明的可能组合。
-
使用“option strict On”和“Infer Off”
Dim MyString = "Random String"无法编译(与您的说法相反),因为缺少As-clause。如果两者都是Off,则字符串实际上是一个对象(如果您尝试MyString.Length,则可以看到它不起作用)。如果 Infer 是On,则字符串文字被正确检测为字符串。 -
@TimSchmelter:对于第一个示例,您没有看到“Option Infer On”,但在项目级别可能是这样。除非在文件级别被覆盖,否则编译器会使用项目选项设置。
-
@DaveDoknjas:我假设第一个示例使用 option infer on,但第二个示例是 off。但是 OP 提到这确实有效,但事实并非如此。至少如果它仍然是 strict。如果 strict 也是 off 则“字符串”被视为对象。
-
@TimSchmelter:在项目级别,Option Strict 默认关闭,Option Infer 默认开启。这与OP的断言一致。这导致第一个被推断为字符串,第二个被隐式声明为“对象”。
标签: vb.net option-strict option-infer