将VB.Net代码转换为C#时发生逻辑错误 [英] Logic Error while converting VB.Net Code to C#

查看:56
本文介绍了将VB.Net代码转换为C#时发生逻辑错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个VB.Net代码:

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

当我将其转换为C#时,它变为:

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;
    }
}

问题是两个代码的结果不相同.因此VB.net代码执行7次,而C#代码执行4次.

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.

请告诉我是什么问题!

推荐答案

For VB中的边界是预先计算的,在执行循环时不会更改.因此, t.Length Mod 8 会被计算一次,然后使用该值.

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.

在C#中,每次都会评估条件,并且由于您不断更改 t ,因此 t.Length Mod 8 每次都会赋予新值.

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

此外,由于字符串在.NET中是不可变的,因此您的代码最多生成7个 t 的副本.您应该真正做到这一点:

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

这篇关于将VB.Net代码转换为C#时发生逻辑错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆