为什么我不能在 C# 中使用整数作为 while 循环的条件? [英] Why can't I use an integer as a condition for a while loop in C#?
问题描述
在使用如下所示的 while 循环时出现错误,我不明白为什么:
int count = 5;while(count--)//此处显示错误{Console.WriteLine("Number : {0}", count);}
但是,在 C 中,代码可以正常工作.我对为什么会收到此错误感到有些困惑.谁能解释一下为什么?
感谢您抽出宝贵的时间.
C# 没有定义从 int
到 bool
的隐式转换.while
循环条件必须是 bool
.
你应该使用 while(count-- != 0)
代替.
在 C#
中,您有一个 bool
类型,它接受 True
或 False
作为值.在 C
中,除 0
之外的所有内容都为真,0
表示为空.所以你可以在 C
中有 if (1)
但 1
不是 C#
中的逻辑表达式.>
I am getting an error when using the while loop shown below, and I don't understand why:
int count = 5;
while(count--) //here showing an error
{
Console.WriteLine("Number : {0}", count);
}
However, in C, the code works properly. I am a little bit confused about why I am getting this error. Can anyone explain why?
Thanks, for your invaluable time.
C# does not define an implicit conversion from int
to bool
. The while
loop condition must be a bool
.
You should use while(count-- != 0)
instead.
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屋!