我可以在参数中添加if语句吗?

C0d*_*1ng 5 c#

有没有办法在函数参数中添加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
Run Code Online (Sandbox Code Playgroud)

Com*_*hip 6

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

它的形式是

condition ? value_if_true : value_if_false
Run Code Online (Sandbox Code Playgroud)

例如:

Console.Write((!Example) ? "Example is false" : "Example is true");
Run Code Online (Sandbox Code Playgroud)

或者我个人的偏好,

Console.Write(Example ? "Example is true" : "Example is false");
Run Code Online (Sandbox Code Playgroud)

这样我就不必思考"不是Example假" 时会发生什么.

请注意,你不能把任意代码value_if_truevalue_if_false-它必须是一个表达式,而不是一个声明.所以上面的内容是有效的

(!Example) ? "Example is false" : "Example is true"
Run Code Online (Sandbox Code Playgroud)

string,你可以写:

string message = (!Example) ? "Example is false" : "Example is true";
Console.Write(message);
Run Code Online (Sandbox Code Playgroud)

但是,你做不到

(!Example) ? Console.Write("Example is false") : Console.Write("Example is true")
Run Code Online (Sandbox Code Playgroud)

例如,因为Console.Write(..)不返回值,或

(!Example) ? { a = 1; "Example is false" } : "Example is true"
Run Code Online (Sandbox Code Playgroud)

因为{ a = 1; "Example is false" }不是表达.


Nat*_*lor 5

您可能正在寻找三元表达式

if (thisIsTrue)
   Console.WriteLine("this")
else
   Console.WriteLine("that")
Run Code Online (Sandbox Code Playgroud)

相当于:

Console.WriteLine(thisIsTrue ? "this" : "that") 
Run Code Online (Sandbox Code Playgroud)