在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 17:07:23  来源:igfitidea点击:

Adding value to integer in VB.NET

vb.netinteger

提问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 proovinteger 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:

但是值得知道的是,一旦您开始编写多线程应用程序,这会给您带来麻烦,因为增加变量不是原子操作:

  1. Get the value from proov
  2. Increment this value by 1
  3. Store the new value in proov
  1. 从中获取值 proov
  2. 将此值增加 1
  3. 将新值存储在 proov

If a thread yjumps in before thread xcompletes all 3 steps, thread xand ywill end up doing the same thing.

如果一个线程y在线程之前跳x完成所有3个步骤,线程xy最终会做同样的事情。

To prevent that from happening, use the Interlockedclass in the System.Threadingnamespace to Increment()the variable:

为了防止这种情况发生,请使用命名空间中的InterlockedSystem.ThreadingIncrement()变量:

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