【问题标题】:CS0029: Cannot implicitly convert type 'int' to 'bool'CS0029:无法将类型“int”隐式转换为“bool”
【发布时间】:2019-09-30 03:20:47
【问题描述】:

这是 C# 中的一段代码,在执行时它给了我错误

错误:“无法将类型“int”隐式转换为“bool””

我无法理解我已将数组声明为 boolean 变量,并且我的代码中没有其他 int 变量,我的函数参数是否正确并不重要?

private static bool[,] array = new bool[41, 8];

public void SetArrayElement(int row, int col)
{
    array[row, col] = 1;
}

【问题讨论】:

  • array[row, col] = true; 如果你坚持使用1array[row, col] = 1 == 1;(更好)或array[row, col] = (bool)1;
  • “我的代码中没有其他 int” - 您尝试分配的值 1 是一个 int。
  • 忘记Cwhile(1) 应该永远运行。它的C#
  • 我不明白这里的反对意见,这个问题有所有需要的东西。错误消息,重现它的最小且可验证的示例和一个明确的问题。对反对者:至少向他解释一下,他应该改变什么,并在下一次做得更好......
  • @MongZhu 我投了反对票,因为“这个问题没有显示任何研究成果”。这是一个基本 C# 语言问题,可以通过花一点时间学习该语言的基础知识来解决,而不是不打扰并立即点击 Stack Overflow 上的“”按钮。

标签: c# type-conversion int boolean


【解决方案1】:

int 转换为bool 可能会导致信息丢失。 1 是 C# 中的 integer literal。你可以改用true

array[row, col] = true;

【讨论】:

    【解决方案2】:

    您将数组声明为bool,因此您不能将integer 分配给它。您可以改用truefalse

    private static bool[,] array = new bool[41, 8]; 
    
    public void SetArrayElement(int row, int col)
    {
       array[row, col] = true; // assign either true or false.
    }
    

    【讨论】:

      【解决方案3】:

      C 不同,C# 具有特殊的 bool 类型,并且不会将 1 隐式转换为 true: p>

        bool myValue = 1; // <- Compile Time Error (C#)
      

      即使 显式 强制转换是可能的,这也不是一个好主意:

        bool myValue = (bool)1; // It compiles, but not a good style  
      

      在你的情况下,你可以分配true

        //DONE: static : we don't want "this" here
        public static void SetArrayElement(int row, int col)
        {
           //DONE: validate public method's values
           if (row < array.GetLowerBound(0) || row > array.GetUpperBound(0))
               throw new ArgumentOutOfRangeException(nameof(row));
           else if (col < array.GetLowerBound(1) || col > array.GetUpperBound(1))
               throw new ArgumentOutOfRangeException(nameof(col)); 
      
           array[row, col] = true; // true, instead of 1
        }
      

      【讨论】:

        猜你喜欢
        • 2015-03-28
        • 1970-01-01
        • 1970-01-01
        • 2020-10-04
        • 2017-10-05
        • 1970-01-01
        • 1970-01-01
        • 2022-07-06
        • 2017-10-06
        相关资源
        最近更新 更多