VB.NET 中高效的多变量声明和赋值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19859270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Efficient, multiple variable declaration & assignment in VB.NET
提问by shad0w_wa1k3r
Being new to VB.NET, I would like to know which of the following is more efficient in nature (time-wise (which code runs faster), code-neatness-wise, etc. you may add your own reasons too)
作为 VB.NET 的新手,我想知道以下哪一项在本质上更有效(时间方面(哪些代码运行速度更快)、代码整洁方面等,您也可以添加自己的理由)
Dim a, b, c, d As Integer
a = 1
b = 2
c = 3
d = 4
OR
或者
Dim a As Integer = 1
Dim b As Integer = 2
Dim c As Integer = 3
Dim d As Integer = 4
I am mainly asking this because my code has way too many Dimstatements & coming from a Python background, I have never ever seen soooo many declarations (I do need those though, trust me). Is this okay? Or am I coding in a bad style?
我问这个主要是因为我的代码有太多的Dim语句并且来自 Python 背景,我从来没有见过这么多的声明(尽管我确实需要这些,相信我)。这个可以吗?还是我的编码风格不好?
回答by nunzabar
Runtime performance will be identical, as they both compile to the same IL.
运行时性能将相同,因为它们都编译为相同的 IL。
.locals init ([0] int32 a,
[1] int32 b,
[2] int32 c,
[3] int32 d)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldc.i4.2
IL_0003: stloc.1
IL_0004: ldc.i4.3
IL_0005: stloc.2
IL_0006: ldc.i4.4
IL_0007: stloc.3
IL_0008: ret
Style-wise, I would avoid declaring multiple variables on one line (as in your first example). One "concept" per line is easier to read - as you don't have to visually parse commas.
在风格方面,我会避免在一行中声明多个变量(如你的第一个例子)。每行一个“概念”更容易阅读 - 因为您不必直观地解析逗号。
回答by Ric
For the sake of clarity, perhaps one variable per line with an assignment for me personally is easier to look at and much clearer.
为了清楚起见,也许每行一个变量对我个人来说是一个赋值更容易看也更清楚。
I mean you can do this:
我的意思是你可以这样做:
Dim a As Single = 1, b As Single = 2, x As Double = 5.5, y As Double = 7.5
取自这里。
But things start to look a bit difficult at this point. It is entirely a prefernce thing I suppose!
但在这一点上,事情开始看起来有点困难。我想这完全是一种偏好!
回答by DHUNPUT KHEMRAJ
Both options are ok. Still if you are not happy then you can create an array as all variables are of the same data types. Hope that helps.
两个选项都可以。如果您不满意,那么您可以创建一个数组,因为所有变量都具有相同的数据类型。希望有帮助。

