在 VB.NET 中为整数添加值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18569823/
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
Adding value to integer in VB.NET
提问by TheCreepySheep
How do I add +1 value to an integer?
如何将 +1 值添加到整数?
Something like
就像是
Do
If myClientMachineIP.AddressFamily = Sockets.AddressFamily.InterNetwork Then
Label2.Text = myClientMachineIP.ToString()
Else
TextBox2.Text = "IP is not equal to IPv4"
proov = +1
TextBox3.Text = proov
End If
Loop Until proov = 10
How do I add +1 to the proov
integer variable?
如何将 +1 添加到proov
整数变量?
回答by Tim
CORRECTION
更正
VB.NET does not have the increment operator (++
), so the simplest way would be to use the addition assignment operator += Operator:
VB.NET 没有自增运算符 ( ++
),因此最简单的方法是使用加法赋值运算符+= 运算符:
proov += 1
Another way is to explicitly add 1 to the value:
另一种方法是显式地将 1 添加到值中:
proov = proov + 1
回答by Steven Liekens
As is already suggested multiple times, simply adding 1 will usually suffice:
正如已经多次建议的那样,简单地添加 1 通常就足够了:
proov += 1
But it's worth knowing that this can get you in trouble once you start writing multithreaded applications, because incrementing a variable is not an atomic operation:
但是值得知道的是,一旦您开始编写多线程应用程序,这会给您带来麻烦,因为增加变量不是原子操作:
- Get the value from
proov
- Increment this value by 1
- Store the new value in
proov
- 从中获取值
proov
- 将此值增加 1
- 将新值存储在
proov
If a thread y
jumps in before thread x
completes all 3 steps, thread x
and y
will end up doing the same thing.
如果一个线程y
在线程之前跳x
完成所有3个步骤,线程x
和y
最终会做同样的事情。
To prevent that from happening, use the Interlocked
class in the System.Threading
namespace to Increment()
the variable:
为了防止这种情况发生,请使用命名空间中的Interlocked
类System.Threading
到Increment()
变量:
If myClientMachineIP.AddressFamily = Sockets.AddressFamily.InterNetwork Then
Label2.Text = myClientMachineIP.ToString()
Else
TextBox2.Text = "IP does not equal to IPv4"
TextBox3.Text = Threading.Interlocked.Increment(proov)
End If
回答by bgs
Simply try this:
简单地试试这个:
proov++
证明++
or
或者
TextBox2.Text = "IP does not equal to IPv4"
proov = proov + 1
TextBox3.Text = proov