Logic Error while converting VB.Net Code to C#

2019-08-15 12:03发布

问题:

I have this VB.Net Code:

Dim t as String = "111100111000011110111110010111101001100001100011101000001010011100110110100110100000101001110010011001101"
Dim i as Integer
If (t.Length Mod 8) <> 0 Then
    For i = 1 To 8 - (t.Length Mod 8)
        t = "0" + t
    Next
End If

When I convert it to C# it becomes:

string t = "111100111000011110111110010111101001100001100011101000001010011100110110100110100000101001110010011001101";

int i = 0;
if ((t.Length % 8) != 0)
{
    for (i = 1; i <= (8 - (t.Length%8)); i++)
    {
        t = "0" + t;
    }
}

The problem is the two codes are not same result. so the VB.net code is executing 7 times and the C# code is executing 4 times.

Please tell me what is the problem!

回答1:

For boundaries in VB are pre-calculated and do not change while the loop is executed. So t.Length Mod 8 is calculated once and then this value is used.

In C# the condition is evaluated each time, and because you keep changing t, t.Length Mod 8 gives new value each time.

Also because strings are immutable in .NET, your code generates up to 7 copies of t. You should really do this:

Dim diff As Integer = t.Length Mod 8

If diff <> 0 Then
    t = New String("0"c, 8 - diff) & t
End If