CS0029:无法将类型'int'隐式转换为'bool'

时间:2019-05-13 07:38:50

标签: c# type-conversion int boolean

这是C#中执行时的大量代码,给我错误

  

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

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

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

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

3 个答案:

答案 0 :(得分:3)

您将数组声明为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.
}

答案 1 :(得分:3)

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

array[row, col] = true;

答案 2 :(得分:3)

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

true

即使可以进行显式强制转换,也不是一个好主意:

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

根据您的情况,您只需分配 bool myValue = (bool)1; // It compiles, but not a good style

true