首页 文章

VB.NET相当于C#var关键字[重复]

提问于
浏览
143

这个问题在这里已有答案:

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

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

4 回答

  • -1

    Option Infer必须为 on 才能使其正常运行 . 如果是这样,那么省略VB.NET(Visual Basic 9)中的类型将隐式键入变量 .

    这与以前版本的VB.NET中的"Option Strict Off"不同,因为变量是强类型的;它只是隐式地(如C# var )关键字完成的 .

    Dim foo = "foo"
    

    foo 被声明为 String .

  • 15

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

    Dim query = From x In y Where x.z = w Select x
    

    与其他一些答案相反,您不需要 Option Strict On .

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

    Function MyVarType(Of T)(ByRef Var As T) As Type
        Return GetType(T)
    End Function
    

    详细地:

    • 没有 Dim

    Explicit Off ,给 Object

    Explicit On ,错误"Name '' is not declared."

    • Dim

    • Infer On ,给出预期的类型

    • Infer Off

    Strict On ,错误"Option Strict On requires all declarations to have an 'As' clasue."

    Strict Off ,给 Object

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

  • 44

    只需使用传统的 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
    
  • 138

    Object 在这个例子中为我工作

    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
    

相关问题