C# CS0029:无法隐式转换类型';int';至';布尔';

C# CS0029:无法隐式转换类型';int';至';布尔';,c#,type-conversion,int,boolean,C#,Type Conversion,Int,Boolean,这是C语言中的一段代码,在执行时它给了我一个错误 错误:“无法将类型“int”隐式转换为“bool” 我无法理解我已经将数组声明为boolean变量,并且在我的代码中没有其他int变量,我的函数参数正确与否无关紧要 private static bool[,] array = new bool[41, 8]; public void SetArrayElement(int row, int col) { array[row, col] = 1; } 您将数组声明为bool,因此无法将

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

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

我无法理解我已经将数组声明为
boolean
变量,并且在我的代码中没有其他
int
变量,我的函数参数正确与否无关紧要

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

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

您将数组声明为
bool
,因此无法将
integer
赋值给它。您可以改用
true
false

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

public void SetArrayElement(int row, int col)
{
   array[row, col] = true; // assign either true or false.
}
array[row, col] = true;

int
转换为
bool
可能会导致信息丢失<代码>1是C#中的一个。您可以改用
true

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

public void SetArrayElement(int row, int col)
{
   array[row, col] = true; // assign either true or false.
}
array[row, col] = true;

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

  bool myValue = 1; // <- Compile Time Error (C#)
在您的情况下,您可以只指定
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
  }
//完成:静态:我们不希望这里出现“this”
公共静态void SetArrayElement(int行,int列)
{
//完成:验证公共方法的值
if(rowarray.GetUpperBound(0))
抛出新ArgumentOutOfRangeException(nameof(row));
else if(colarray.GetUpperBound(1))
抛出新ArgumentOutOfRangeException(nameof(col));
数组[行,列]=true;//true,而不是1
}

数组[行,列]=true
如果坚持
1
array[row,col]=1==1(更好)或
数组[行,列]=(bool)1
“我的代码中没有其他int”-您试图分配的值,
1
,是一个int。忘记
C
其中的
,而(1)
应该永远运行。它的
C#
我不明白这里的反对票,这个问题有所有需要的东西。错误消息,最小的和可验证的例子来重现它和一个明确的问题。对下一次投票的人:至少向他解释一下,他应该改变什么,让下一次变得更好……@MongZhu我投了反对票,因为“这个问题没有显示任何研究成果”。这是一个基本的C#语言问题,可以通过花一点时间学习该语言的基础知识来解决,而不是不费吹灰之力,立即点击堆栈溢出上的“提问”按钮。