无法将int隐式转换为bool

时间:2011-07-13 16:51:14

标签: c#

好的,所以我得到了“无法将int转换为bool”错误。

我正在尝试转换此VB .net代码:

Function GetChecksum(ByVal Source As String) As Long
    Dim iVal, Weight, CheckHold, CheckSum As Long
    Weight = 1
    CheckSum = 0
    For iVal = 1 To Len(Source)
        CheckHold = Asc(Mid$(Source, iVal, 1)) * Weight
        CheckSum = CheckSum + CheckHold
        Weight = Weight + 2
    Next iVal
    GetChecksum = CheckSum Mod &H7FFFFFFF
End Function

我已经到了这里:

    public long getCheckSum(string source)
    {
        long iVal, weight, checkgold, checksum = new long();
        weight = 1;
        checksum = 0;
        for (iVal = 1; Strings.Len(source);)
        {

        }
    }

问题是“For(iVal = 1; Strings.Len(source);)”代码。我正在使用“Microsoft.VisualBasic”。我现在不知道该怎么做。如果你能帮助我那就太好了。

8 个答案:

答案 0 :(得分:4)

看起来你需要正确设置你的循环。在C#中,for循环(通常)遵循以下格式:

for(initializer; conditional check; evaluation)
  • 初始化程序是您设置iVal = 1
  • 等变量的地方
  • 条件检查是确定for循环边界的地方
  • 评估通常是增加变量的地方

在你的代码中,你有一个整数,Strings.Len(source),作为条件检查,它期望一个布尔响应,所以它失败了。

你的for loop开启者应该是这样的:

for (iVal = 1; iVal < source.Length; iVal++)

假设你的逻辑是0&lt; iVal&lt;源字符串的长度。

顺便说一下,在C#中检查字符串长度的方法是使用.Length属性,而不是使用Strings.Len()函数。

答案 1 :(得分:3)

    for (iVal = 1; iVal < source.Length; iVal++)
    {

    }

中间部分是一个条件。

答案 2 :(得分:3)

您将需要:

  for (iVal = 1; iVal <= source.Length; ival += 1)

但要注意这个循环通过1..source.Length,
不是更常见的(在C#中)0..source.Length-1

答案 3 :(得分:0)

您的For语法应如下所示:

For(ival = 1; source.Length; ival++)
{
  // your code here
}

ival ++将取代VB中的“Next”。

答案 4 :(得分:0)

由于其他人已经解决了您的问题,我只想添加以供您日后参考,您可能需要查看Convert VB to C#

我自己在很多场合都使用过它,效果非常好。

答案 5 :(得分:0)

for循环的标准语法:

for(counter initialize; counter compare; counter increment) {}

比较需要bool,您提供int Strings.Len(source),它会返回一些数字,而不是像true或{{1}这样的布尔值}。

尝试

false

您可能希望使用for(iVal = 1; iVal < String.Len(source); iVal++) ,因为从1开始或将<=设置为0

答案 6 :(得分:0)

我不是将for循环字面翻译成C#,而是使用foreach,因为您对序列的元素(字符串中的每个字符)进行了直接的迭代:

public long getCheckSum(string source)
{
  long checkHold = 0, checkSum = 0, weight = 1;

  foreach (char ch in source)
  {
    checkHold = (long)ch * weight;
    checkSum += checkHold;
    weight += 2;
  }

  return checkSum % 0x7FFFFFFF;
}

答案 7 :(得分:-1)

你想要

for (iVal = 1; iVal <= source.Length; iVal++)
{
    //your code here
}

或者,如果你想单独留下iVal(因为你以后需要它“纯粹”)

for(i = iVal; i <= source.Length; i++)
{
    //your code here.
}