c# - 如何在 C# 中执行 C++ 逗号 + 三元运算符?

标签 c# functional-programming

我最近还在学习C#,当我试图将这个带三元运算符的C++逗号运算符转换为C#代码时,我被文档困住了:

这是 C++ 代码:

#include <iostream>
using namespace std;

int main() {

  bool test1 = false;
  bool test2 = true;

  cout << 
    ((test1) ? 
      "pass me" : 
      (test1 = true, (test2) ?        //Comma inside test condition
        ((test1) ? 
          (test1 = false, "get me") : //Comma inside return condition
          "pass me") : 
        "pass me")) << endl;

  return 0;
}

但是当我尝试用 C# 来做时

using System.IO;
using System;

class Program {
  static void Main() {
    bool test1 = false;
    bool test2 = true;

    Console.WriteLine( ((test1) ? 
                         "pass me" : 
                         ((test1 = true, test2) ? 
                           "get me" : 
                           "pass me")));
  }
}

C# 似乎不支持它,所以我想知道如何为其构建代码。

谢谢。

最佳答案

您最好将整个表达式重构为单独的函数。

像这样:

private static bool EvaluateTest(ref bool test1, ref bool test)
{
  if (test1) {
    return "pass me";
  } else {
    test1 = true;
    if (test2) {
      if (test1) {
        test1 = false;
        return "get me";
      } else {
        return "pass me";
      }
    } else {
      return "pass me";
    }
  }
}

我认为这是正确的,但我还没有测试过。这个表达式很难理解,所以我可能在某个地方错过了一些东西(而且我已经有一段时间没有编写 C# 代码了),但这至少让我明白了我在说什么。

这里的逻辑甚至没有意义,因为如果我正确地读取原始表达式,test1 在最后一个 if (test1) 中将始终为 true测试...如果你像这样写清楚的话,一些事情就会变得显而易见。

如果您必须使用这样的嵌入式三元运算符编写表达式,至少使用正确的缩进,即像使用嵌套的 if-else block 一样缩进它.

关于c# - 如何在 C# 中执行 C++ 逗号 + 三元运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22178684/

相关文章:

c# - 添加新的 Jtoken 到 Json Jtoken

c# - 将数据网格的选定行加载到标签

c# - 运行组合框中显示的 .pdf 最简单的方法是什么?

c# - 用 Either/Maybe/Option 替换异常

memory - 不可变可以是内存 pig 吗?

c# - 查找类型参数的类型

c# - 同时在逗号和空格上拆分字符串

scala - 用于包装不纯方法的效果?

functional-programming - 使用 OCAML 中提供的高阶函数检查树是否是 BST

java - 如何通过消除所有空/空条目来折叠二维数组