为什么我不能在C#中使用整数作为while循环的条件? [英] Why can't I use an integer as a condition for a while loop in C#?

查看:118
本文介绍了为什么我不能在C#中使用整数作为while循环的条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以这种方式使用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#没有定义从intbool的隐式转换. 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类型,该类型接受TrueFalse作为值.在C中,除0之外的所有其他内容均为true,并且0指示为null.因此,可以在C中包含if (1),但1C#中不是逻辑表达式.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆