VB.Net 变量声明
我注意到,即使同时打开 Option Strict 和 Option Explicit ,这两个编译器也不会出现任何编译器警告或错误:
Dim x As Exception = New Exception("this is a test")
Dim y = New Exception("this is another test")
我的问题是,使用第一种方式(参见变量 x)还是第二种方式(参见变量 y)?我的猜测是,VB 不需要 As
子句,因为变量已就地初始化,因此编译器可以推断类型。
我倾向于喜欢第一种方式,因为它只是“感觉”正确,并且与 C# 等其他语言更一致,只是想知道一种方式是否优于另一种方式是否有充分的理由。我想这确实是个人选择。
I notice that both of these compile without any compiler warnings or errors, even with Option Strict
and Option Explicit
both turned on:
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)? 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.
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. I guess it's really personal choice.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看看 Option Infer On 的奇妙之处吧,编译器会自动计算出“y”的类型。自 VS2008 起可用。通过关闭它,您会得到您正在寻找的错误:
Behold the wonder of Option Infer On, the compiler figures out the type of "y" automatically. Available since VS2008. You'll get the error you are looking for by turning it off:
我会做
Dim x As New Exception("this is a test")
。两全其美,无需推断,但您仍然只需键入 Exception 一次:)I'd do
Dim x As New Exception("this is a test")
. Best of both worlds, no infering but you still only have to typeException
once :)Option Infer
控制此编译器功能。两者是等价的——这类似于关于是否使用var
关键字的(无实际意义的)C# 争论。我的两分钱意见是将其留给个人开发人员,但许多人可能会说建立一个约定并遵循它。Option Infer
is what controls this compiler feature. Both are equivalent--this is similar to the (moot) C# debate about whether to use thevar
keyword. 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 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.