为什么for循环的行为会有所不同

为什么for循环的行为会有所不同

本文介绍了将VB.NET代码迁移到C#时,为什么for循环的行为会有所不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将项目从Visual Basic迁移到C#,并且不得不更改声明使用的for循环的方式.

I'm in the process of migrating a project from Visual Basic to C# and I've had to change how a for loop being used is declared.

在VB.NET中,for循环在下面声明:

In VB.NET the for loop is declared below:

Dim stringValue As String = "42"

For i As Integer = 1 To 10 - stringValue.Length
   stringValue = stringValue & " " & CStr(i)
   Console.WriteLine(stringValue)
Next

哪个输出:

42 1
42 1 2
42 1 2 3
42 1 2 3 4
42 1 2 3 4 5
42 1 2 3 4 5 6
42 1 2 3 4 5 6 7
42 1 2 3 4 5 6 7 8

在C#中,以下声明了for循环:

In C# the for loop is declared below:

string stringValue = "42";

for (int i = 1; i <= 10 - stringValue.Length; i ++)
{
   stringValue = stringValue + " " + i.ToString();
   Console.WriteLine(stringValue);
}

输出:

42 1
42 1 2
42 1 2 3

这显然是不正确的,因此我不得不稍稍更改代码,并包含一个可以容纳字符串长度的整数变量.

This obviously isn't correct so I had to change the code ever so slightly and included an integer variable that would hold the length of the string.

请参见下面的代码:

string stringValue = "42";
int stringValueLength = stringValue.Length;

for (int i = 1; i <= 10 - stringValueLength; i ++)
{
   stringValue = stringValue + " " + i.ToString();
   Console.WriteLine(stringValue);
}

输出:

42 1
42 1 2
42 1 2 3
42 1 2 3 4
42 1 2 3 4 5
42 1 2 3 4 5 6
42 1 2 3 4 5 6 7
42 1 2 3 4 5 6 7 8

现在我的问题解决了,即使每次循环发生时,字符串的长度都会改变,Visual Basic在for循环中使用stringValue.Length条件在Visual Basic方面与C#有何不同.在C#中,如果我在for循环条件中使用stringValue.Length,则每次循环发生时它都会更改初始字符串值.为什么会这样?

Now my question resolves around how Visual Basic differs to C# in terms of Visual Basic using the stringValue.Length condition in the for loop even though each time the loop occurs the length of the string changes. Whereas in C# if I use the stringValue.Length in the for loop condition it changes the initial string value each time the loop occurs. Why is this?

推荐答案

在C#中,每次迭代都会评估循环边界条件.在VB.NET中,仅在进入循环时对其进行评估.

In C#, the loop boundary condition is evaluated on each iteration. In VB.NET, it is only evaluated on entry to the loop.

因此,在所涉及的C#版本中,由于stringValue的长度在循环中被更改,因此最终循环变量值将被更改.

So, in the C# version in the question, because the length of stringValue is being changed in the loop, the final loop variable value will be changed.

在VB.NET中,最终条件是包容性的,因此在C#中将使用<=而不是<.

In VB.NET, the final condition is inclusive, so you would use <= instead of < in C#.

C#中的结束条件评估具有一个推论,即即使它没有变化,但计算起来很昂贵,但也应该在循环之前进行一次计算.

The end condition evaluation in C# has the corollary that even if it doesn't vary but it is expensive to calculate, then it should be calculated just once before the loop.

这篇关于将VB.NET代码迁移到C#时,为什么for循环的行为会有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:58