[英]CS0029: Cannot implicitly convert type 'int' to 'bool'
Here is a chunk of code in C# on execution it gives me error 这是执行时C#中的一大段代码,它给了我错误
ERROR: "Cannot implicitly convert type “int” to “bool” "
错误:“无法将类型“ int”隐式转换为“布尔””
I am unable to understand that I have declared array as boolean
variable and there is no other int
variable in my code and it doesn't matter what my function arguments are right? 我无法理解我已将数组声明为
boolean
变量,并且我的代码中没有其他int
变量,并且我的函数参数是正确的没关系吗?
private static bool[,] array = new bool[41, 8];
public void SetArrayElement(int row, int col)
{
array[row, col] = 1;
}
You declared array as bool
so you can not assign integer
to it. 您将数组声明为
bool
因此无法为其分配integer
。 You can use true
or false
instead. 您可以改用
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.
}
Conversion from int
to bool
might result in lost information. 从
int
转换为bool
可能会导致信息丢失。 1
is an integer literal in C#. 1
是C#中的整数文字 。 You can use true
instead. 您可以改用
true
。
array[row, col] = true;
Unlike C , C# has special bool
type and doesn't cast implicitly 1
to true
: 与C不同, C#具有特殊的
bool
类型,并且不会隐式将1
强制转换为true
:
bool myValue = 1; // <- Compile Time Error (C#)
Even if explicit cast is possible, it's not a good idea: 即使可以进行显式强制转换,也不是一个好主意:
bool myValue = (bool)1; // It compiles, but not a good style
In your case you can just assign true
在您的情况下,您可以分配
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.