while循环在C#中有多个条件

Hei*_*idi 5 .net c# while-loop conditional-statements

这是我的代码:

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

  mydata.x = x;
 }
Run Code Online (Sandbox Code Playgroud)

问题是我想result = Func(x)在while条件中使用,因为结果将在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); 
Run Code Online (Sandbox Code Playgroud)

在我的项目中,因为它第一次调用Func(x),这是我不想要的.但我试过while(result = Func(x) != ERR_D),它不起作用.任何解决这个问题的想法?

Gen*_*ene 8

你只需要添加一些括号:

while((result = Func(x)) != ERR_D) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

!=经营者具有比分配更高的优先级,所以你需要强制编译器先进行分配(计算结果为C#中的分配值),在两侧比较值之前!=相互操作.这是您经常看到的模式,例如读取文件:

string line;

while ((line = streamReader.ReadLine()) != null) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)


Dar*_*ren 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);
 }
Run Code Online (Sandbox Code Playgroud)