为什么我不能在C#中使用整数作为while循环的条件? [英] Why can't I use an integer as a condition for a while loop in C#?
问题描述
以这种方式使用while循环时出现错误,我不明白为什么:
I am getting an error using while loop in this manner, and I don't understand why:
int count = 5;
while(count--) //here showing an error
{
Console.WriteLine("Number : {0}", count);
}
但是,在C语言中,代码可以正常工作.我对为什么会收到此错误感到有些困惑.谁能解释为什么?
However, in C, the code works properly. I am little bit confused about why I am getting this error. Can anyone explain why?
推荐答案
C#没有定义从int
到bool
的隐式转换. while
循环条件必须为bool
.
C# does not define an implicit conversion from int
to bool
. The while
loop condition must be a bool
.
您应该改用while(count-- != 0)
.
在C#
中,您具有bool
类型,该类型接受True
或False
作为值.在C
中,除0
之外的所有其他内容均为true,并且0
指示为null.因此,可以在C
中包含if (1)
,但1
在C#
中不是逻辑表达式.
In C#
you have a bool
type which accepts True
or False
as value. In C
everything other than 0
is true and 0
indicates null. So you can have if (1)
in C
but 1
is not a logical expression in C#
.
这篇关于为什么我不能在C#中使用整数作为while循环的条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!