C#中的while循环与多个条件

5
这是我的代码:
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),它不起作用。有什么解决方法吗?

2
嗯,x 从来没有改变过。也许这与此有关?很难说,因为“不起作用”几乎可以意味着任何事情,而我们不知道应该发生什么。 - Ant P
var result = Func(x); while (result != ERR_D) { doStuff(); result = Func(x); } - Corak
在 while 循环中抛出异常真的有意义吗?一旦抛出异常,循环就会终止... - Stig-Rune Skansgård
5个回答

8
您只需要添加一些括号:
while((result = Func(x)) != ERR_D) { /* ... */ }
!= 运算符的优先级高于赋值,因此您需要强制编译器先执行赋值(在 C# 中计算为分配的值),然后再将 != 运算符两边的值进行比较。这是一个经常看到的模式,例如读取文件时:
string line;

while ((line = streamReader.ReadLine()) != null) { /* ... */ }

6

尝试在循环之外声明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);
 }

2

试试这个:

while((result=Func(x)) != ERR_D){
 if(result == ERR_A) 
      throw...; 
 if(result == ERR_B)
      throw...;
 mydata.x = x;
}

注意:在括号中首先完成赋值操作(result=Func(x)),实际上是由运算符=的重载完成的,该运算符返回左侧操作数的引用,即result。之后,将使用运算符!=resultERR_D进行比较。


1

尝试

while((result = Func(x)) != ERR_D)

0
你可以使用 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;     
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接