如何在C#中使用C ++逗号+三元运算符?

时间:2014-03-04 17:21:23

标签: 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#似乎不支持它,所以我想知道如何为它构建代码。

谢谢。

2 个答案:

答案 0 :(得分:4)

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

像这样:

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)测试中始终为真......如果你这样写得很清楚。

如果你必须使用这样的嵌入式三元运算符编写表达式,至少使用适当的缩进,即缩进它,就像嵌套的if-else块一样

答案 1 :(得分:0)

我永远不会这样编码,但在C#中,逗号运算符不能像您的代码中所示那样工作。然而,这将起作用(如果你这样做,则编码不好)。

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

基于我所看到的,你不需要将test1设置为true,而是检查test2的状态。假设如果test1为false,则test2是您检查的下一个条件。

 Console.WriteLine( (test1) ? "pass me" 
                       : (test2) ? "get me" 
                                 : "pass me");