gpt4 book ai didi

vb.net - 为什么 VB.Net 类型推断在类字段中不起作用?

转载 作者:行者123 更新时间:2023-12-01 15:28:47 25 4
gpt4 key购买 nike

如果我要在方法体中键入以下内容:

Dim myInt = 1

Visual Studio IDE(因此,我猜是编译器)将 myInt 的类型推断为 Integer

编辑

显然在这里使用文字是一个糟糕的选择,因为我已经卷入了一场与问题无关的冗长辩论。如果您对表达式 1 可能被解释为不同数字类型的实例这一事实有异议,请假装我写过:

Dim myInstance = New MyClass()

结束编辑

但是,当我将具有完全相同代码的字段声明放在 的顶部时,不会推断myList 的类型:

Public Class Foo
Dim myInt = 1
End Class

在鼠标悬停时,它提到缺少 As 子句,并表示已假定一种 Object 类型。我无法将 myInt 作为参数传递给需要 Integer 参数的函数或 sub,而不显式添加 As 子句或强制转换为 Integer。

IDE 和编译器处理类型推断的方式是否存在差异?另一方面,如果编译器在这种情况下也无法推断类型,那么为什么方法变量和类字段之间存在差异?

最佳答案

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

Local type inference applies at procedure level. It cannot be used to declare variables at module level (within a class, structure, module, or interface but not within a procedure or block). If num2 in the previous example were a field of a class instead of a local variable in a procedure, the declaration would cause an error with Option Strict on, and would classify num2 as an Object with Option Strict off. Similarly, local type inference does not apply to procedure level variables declared as Static.

关于vb.net - 为什么 VB.Net 类型推断在类字段中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16900305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com