Logic Error while converting VB.Net Code to C#

纵然是瞬间 提交于 2020-01-06 01:45:29

问题


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


来源:https://stackoverflow.com/questions/29489907/logic-error-while-converting-vb-net-code-to-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!