c# - while 在 C# 中使用多个条件循环

标签 c# .net while-loop conditional-statements

这是我的代码:

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/

相关文章:

c# - 使用 c#.net winforms 从 mysql 数据库中选择 - 如何检查响应?

c# - 从 C# (.NET) 调用 Python 函数

bash - While 循环在 Bash 中的第一行之后停止读取

javascript - 初学者 - while 循环中的 document.write

c# - 如何实现我自己的字节数组创建和处理

c# - 如何在自定义 ASP.NET 控件中使用 ScriptManagerProxy?

c# - Parallel.ForEach 中的异常堆栈跟踪和聚合

c# - 如何从 cmd 获取参数到正在运行的 WPF 应用程序

c# - 具有两个不同子集合的自定义配置部分

java - Java 中的符号表