VB.NET相当于C#var关键字

Jac*_*ack 145 c# linq vb.net var keyword

是否存在与C#var关键字等效的VB.NET ?

我想用它来检索LINQ查询的结果.

Ada*_*son 142

选项推断必须打开才能使其正常运行.如果是这样,那么省略VB.NET(Visual Basic 9)中的类型将隐式键入变量.

这是一样的"选项严格关"在VB.NET以前的版本,作为变量强类型; 它只是隐式地(如C#var)关键字完成的.

Dim foo = "foo"
Run Code Online (Sandbox Code Playgroud)

foo被宣布为String.

  • @Quandry:不,不是 (3认同)

Mar*_*urd 45

您需要Option Infer On然后只使用Dim关键字,因此:

Dim query = From x In y Where x.z = w Select x
Run Code Online (Sandbox Code Playgroud)

相反,一些其他的答案,你并不需要Option Strict On.

如果您正在使用VS IDE,您可以将鼠标悬停在变量名称上,但是要获取编译时类型的变量(GetType(variableName)不编译 - "Type'<variablename>'未定义." - VarType(variable)实际上只是VB版本variable.GetType()在运行时返回存储在变量中的实例的类型)我用过:

Function MyVarType(Of T)(ByRef Var As T) As Type
    Return GetType(T)
End Function
Run Code Online (Sandbox Code Playgroud)

详细地:

  • 没有Dim:

    Explicit Off,给 Object

    Explicit On,错误"名称''未声明."

  • Dim:

    • Infer On,给出预期的类型
    • Infer Off:

      Strict On,错误"Option Strict On要求所有声明都有'As'clasue."

      Strict Off,给 Object

正如我在评论中提到的,还有其他的原因,为什么Option Strict On允许LINQ到更有效地执行.具体来说,虽然有许多解决方法,但您无法Into Max(Anon.SomeString)使用它Option Strict Off.


Kon*_*lph 15

只需使用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
Run Code Online (Sandbox Code Playgroud)