这是我的代码:
while( Func(x) != ERR_D)
{
if(result == ERR_A)
throw...;
if(result == ERR_B)
throw...;
mydata.x = x;
}
问题是我想在 while 条件中使用 result = Func(x)
因为结果将在 while 循环内检查。 while 循环应该调用 Func(x)
直到它返回 ERR_D
。
我不会用
do{
result = Func(x);
if(result == ERR_A)
throw ...;
if(result == ERR_B)
throw ...;
mydata.x = x;
}while(result != ERR_D);
在我的项目中,因为它首先调用了 Func(x)
,这是我不想要的。
但是我试过 while(result = Func(x) != ERR_D)
,它不起作用。有解决这个问题的想法吗?
最佳答案
你只需要添加一些括号:
while((result = Func(x)) != ERR_D) { /* ... */ }
!=
运算符的优先级高于赋值,因此您需要强制编译器先执行赋值(在 C# 中计算为赋值),然后再比较值!=
运算符的两边相互连接。这是您经常看到的模式,例如读取文件:
string line;
while ((line = streamReader.ReadLine()) != null) { /* ... */ }
关于c# - while 在 C# 中使用多个条件循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18977022/