while 在具有多个条件的 C# 中循环
本文关键字:循环 条件 while | 更新日期: 2023-09-27 18:32:28
这是我的代码:
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) { /* ... */ }
尝试在循环外部声明result
,然后在每次迭代时为其分配Funcs
返回值。
例如:
var result = Func(x);
while(result != ERR_D)
{
if(result == ERR_A)
throw...;
if(result == ERR_B)
throw...;
mydata.x = x;
result = Func(x);
}
试试这个:
while((result=Func(x)) != ERR_D){
if(result == ERR_A)
throw...;
if(result == ERR_B)
throw...;
mydata.x = x;
}
注意:赋值首先在括号(result=Func(x))
中完成,这个赋值实际上是由运算符=
的重载完成的,这个运算符返回对左侧操作数的引用,即result
。之后,result
将通过操作员!=
与ERR_D
进行比较。
尝试
while((result = Func(x)) != ERR_D)
<</div>
div class="answers">您可以使用while (true)...
来表达这一点:
while (true)
{
var result = Func(x);
if (result == ERR_D)
break;
if (result == ERR_A)
throw ...;
if (result == ERR_B)
throw ...;
mydata.x = x;
}
这是一个只有一个出口的循环(如果你忽略抛出;)),所以它是一个结构化的循环。
你也可以使用for
循环,虽然它看起来有点时髦(双关语不是故意的!
for (var result = Func(x); result != ERR_D; result = Func(x))
{
if (result == ERR_A)
throw ...;
if (result == ERR_B)
throw ...;
mydata.x = x;
}