3

If I were to type the following into a method body:

Dim myInt = 1

the Visual Studio IDE (and therefore, I am guessing, the compiler) infers the type of myInt to be Integer.

EDIT

Apparently using a literal was a bad choice here, since I've become embroiled in a lengthy debate that has nothing to do with the question. If you take issue with the fact that the expression 1 might be interpreted as an instance of different numeric types, pretend I had written:

Dim myInstance = New MyClass()

END EDIT

However, when I put a field declaration with the exact same code at the top of a class, the type of myList is not inferred:

Public Class Foo
    Dim myInt = 1
End Class

On mouseover, it mentions the absence of an As clause, and says a type of Object has been assumed. I cannot pass myInt as an argument to a function or sub that expects an Integer argument, without explicitly adding an As clause or casting to Integer.

Is there a discrepancy between how the IDE and compiler deal with type inference? If, on the other hand, the compiler can't infer type in this situation either, why the discrepancy between method variables and class fields?

4

1 回答 1

3

你发现的东西是故意的。这是MSDN的解释。

本地类型推断适用于过程级别。它不能用于在模块级别声明变量(在类、结构、模块或接口内,但不在过程或块内)。如果前面示例中的 num2 是类的字段而不是过程中的局部变量,则声明将在 Option Strict 开启时导致错误,并将 num2 分类为在 Option Strict 关闭时的对象。同样,局部类型推断不适用于声明为静态的过程级变量。

于 2013-06-03T20:02:02.530 回答