无法将int隐式转换为bool

本文关键字:转换 bool int | 更新日期: 2023-09-27 18:02:31

好的,所以我得到了一个"无法将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"。我只是不知道现在该怎么办。如果你能帮我,那就太好了。

无法将int隐式转换为bool

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

for(initializer; conditional check; evaluation)
  • 初始值设定项是设置变量的地方,比如iVal=1
  • 条件检查用于确定for循环的边界
  • 评估通常是增加变量

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

你的for循环开启器应该看起来像这样:

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

这是假设你的逻辑是0<iVal<源字符串的长度。

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

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

中间部分是一个条件。

您将需要:

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

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

由于其他人已经解决了您的问题,我只想添加一些您可能想要查看"将VB转换为C#"的内容,以供将来参考。

我自己也用过很多次,效果很好。

for循环的标准语法:

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

比较需要bool,而您提供的是带有Strings.Len(source)int,它返回一些数字,而不是像truefalse这样的布尔值。

尝试

for(iVal = 1; iVal < String.Len(source); iVal++)

您可能希望从1开始使用<=,或者将iVal设置为0

您的For语法应该如下所示:

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

ival++将替换VB.

中的"Next">

与其将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;
}

您想要

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

或者,如果你想单独使用iVal(因为你需要它"纯粹"用于以后的用途(

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