简体   繁体   English

VB.Net变量声明

[英]VB.Net variable declaration

I notice that both of these compile without any compiler warnings or errors, even with Option Strict and Option Explicit both turned on: 我注意到,即使同时启用了Option StrictOption Explicit ,这两个文件都可以编译而没有任何编译器警告或错误:

    Dim x As Exception = New Exception("this is a test")
    Dim y = New Exception("this is another test")

My question is, is it more proper to use the first way (see variable x) or the second way (see variable y)? 我的问题是,使用第一种方法(参见变量x)还是第二种方法(参见变量y)更合适? My guess is that VB doesn't need the As clause since the variable is being initialized in place, so the compiler can infer the type. 我的猜测是VB不需要As子句,因为变量已就地初始化,因此编译器可以推断类型。

I tend to like the first way as it just "feels" right and is more consistent with other languages like C# , just wondered if there was some good reason for one way over the other. 我倾向于第一种方法,因为它“感觉”正确,并且与其他语言(例如C# )更加一致,只是想知道是否有某种很好的理由使一种方法优于另一种方法。 I guess it's really personal choice. 我想这真的是个人选择。

Behold the wonder of Option Infer On, the compiler figures out the type of "y" automatically. 看到Option Infer On的奇迹,编译器会自动找出“ y”的类型。 Available since VS2008. 自VS2008起可用。 You'll get the error you are looking for by turning it off: 将其关闭会得到您正在寻找的错误:

Option Strict On
Option Infer Off

Module Module1
    Sub Main()
        Dim x As Exception = New Exception("this is a test")
        Dim y = New Exception("this is another test")   ''# error BC30209
        Dim z As New Exception("this is a third test")
    End Sub
End Module

Option Infer is what controls this compiler feature. Option Infer是控制此编译器功能的因素。 Both are equivalent--this is similar to the (moot) C# debate about whether to use the var keyword. 两者是等效的-这类似于关于是否使用var关键字的COT辩论。 My two-cents is to leave it up to the individual developer, however many people will likely say to establish a convention and follow it. 我的两分钱是让开发人员自己决定的,但是许多人可能会说要建立一个公约并遵守它。

I'd do Dim x As New Exception("this is a test") . 我会做Dim x As New Exception("this is a test") Best of both worlds, no infering but you still only have to type Exception once :) 两全其美,没有推断,但您仍然只需要键入Exception一次即可:)

I think the first one (with the variable type declaration) would be the safest to use. 我认为第一个(带有变量类型声明)将是最安全的使用方式。 If the program is small, it won't really make a difference, but for larger program's, there could be a noticeable compiler lag. 如果程序很小,则不会真正起作用,但是对于较大的程序,可能会有明显的编译器滞后。 So (in my opinion) declaring the type is the best thing to do. 因此(我认为)最好声明类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM