是否有与 C#var
关键字等效的 VB.NET?
我想用它来检索 LINQ 查询的结果。
Option Infer必须打开才能正常运行。如果是这样,那么在 VB.NET (Visual Basic 9) 中省略类型将隐式键入变量。
这与以前版本的 VB.NET 中的“Option Strict Off”不同,因为变量是强类型的;它只是隐含地完成(如 C# var
)关键字。
Dim foo = "foo"
foo
被声明为String
.
您需要Option Infer On
然后只使用Dim
关键字,因此:
Dim query = From x In y Where x.z = w Select x
与其他一些答案相反,您不需要Option Strict On
.
如果您使用的是 VS IDE,您可以将鼠标悬停在变量名称上,但要获取变量的编译时类型(GetType(variableName)
不编译 - “类型 '<variablename>' 未定义。” -VarType(variable)
实际上只是VB版本,variable.GetType()
它返回运行时存储在变量中的实例类型)我使用:
Function MyVarType(Of T)(ByRef Var As T) As Type
Return GetType(T)
End Function
详细地:
没有Dim
:
Explicit Off
, 给出Object
Explicit On
,错误“未声明名称''。”
与Dim
:
Infer On
, 给出预期的类型Infer Off
:
Strict On
, 错误“Option Strict On 要求所有声明都有一个 'As' 子句。”
Strict Off
, 给出Object
正如我在评论中提到的,还有其他原因可以Option Strict On
让 Linq 发挥更大的作用。具体来说,您无法Into Max(Anon.SomeString)
使用Option Strict Off
,尽管有许多解决方法。
只需使用Dim
没有类型的常规关键字。
最小的工作示例:
Option Strict On ' Always a good idea
Option Infer On ' Required for type inference
Imports System
Module MainModule
Sub Main()
Dim i = 42
Dim s = "Hello"
Console.WriteLine("{0}, {1}", i.GetType(), s.GetType())
' Prints System.Int32, System.String '
End Sub
End Module
在这个例子中对象对我有用
C#
JToken projects = client.Search(ObjCode.PROJECT, new { groupID = userGroupID });
foreach( var j in projects["data"].Children()) {
Debug.WriteLine("Name: {0}", j.Value<string>("name"));
}
VB
Dim projects As JToken = client.Search(ObjCode.PROJECT, New With { _
Key .groupID = userGroupID _
})
For Each j As Object In projects("data").Children()
Debug.WriteLine("Name: {0}", j.Value(Of String)("name"))
Next