我最近还在学习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/