我能否向参数添加if语句?

5
有没有办法将 if 语句添加到函数参数中?例如:
static void Main()
{
    bool Example = false;
    Console.Write((if(!Example){"Example is false"}else{"Example is true"}));
}
//Desired outcome of when the code shown above is
//executed would be for the console to output:
//Example is false
4个回答

7
你正在寻找条件运算符三元运算符?::

它的形式为:

condition ? value_if_true : value_if_false

例如:

Console.Write((!Example) ? "Example is false" : "Example is true");

或者是我个人的偏好,

Console.Write(Example ? "Example is true" : "Example is false");

我希望永远不必考虑“当‘not Example为假’时会发生什么”的情况。

请注意,您不能为value_if_truevalue_if_false放置任意代码--它必须是一个表达式,而不是语句。因此,上述内容是有效的,因为

(!Example) ? "Example is false" : "Example is true"

是一个字符串,你可以写成:

string message = (!Example) ? "Example is false" : "Example is true";
Console.Write(message);

然而,你无法做到

(!Example) ? Console.Write("Example is false") : Console.Write("Example is true")

例如,因为Console.Write(..)不返回值,或者。
(!Example) ? { a = 1; "Example is false" } : "Example is true"

因为 { a = 1; "Example is false" } 不是一个表达式。


5
您可能正在寻找三元表达式
if (thisIsTrue)
   Console.WriteLine("this")
else
   Console.WriteLine("that")

等价于:

Console.WriteLine(thisIsTrue ? "this" : "that") 

如果你是一个喜欢复杂代码的粉丝,那么你会很高兴地知道,你可以无限嵌套三元表达式。例如:var x = thisIsTrue ? 1 : thatIsTrue ? 2 : 3等等。 - Nathan Taylor

1
Console.Write(Example?"Example is true":"Example is false");

或者甚至
Console.Write("Example is " + (Example?"True":"False"));

1

抱歉,我正在使用平板电脑进行编码。

您可以像以下这样使用三元运算符(https://msdn.microsoft.com/zh-cn/library/ty67wk28.aspx):

Console.Write(!Example?"Example is false":"Example is true");

基本上,这就像是一个内联的“if”语句。如果问号前面的部分为真,则得到问号和冒号之间的位。如果为假,则得到冒号后面的位。

如果这不太清楚,请回复我,在我使用真正的计算机时,我会尝试提供更清晰的示例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接