问题
I need to print some string based on the true or false of a condition.
For example:
if(i == m) {
Console.WriteLine("Number is valid");
} else {
Console.WriteLine("Number is invalid");
}
How can I check this condition and print a message using conditional operator and with only one Console.WriteLine
?
I was trying:
(i == m) ? Console.WriteLine("Number is valid") : Console.WriteLine("Number is not valid");
I know I'm doing it wrong here. Can someone please tell me the correct way?
回答1:
Try this:
Console.WriteLine("Number is " + ((i == m) ? "valid" : "not valid"));
回答2:
Move your ternary operation inside WriteLine
Console.WriteLine((i == m) ? "Number is valid" : "Number is not valid");
回答3:
The conditional operator is an operator. It returns a value. The value it returns is the value from one of its branches.
Console.WriteLine
is a void
method. It does not return a value. As a result, you cannot use it as one of the branches of the conditional operator.
BTW, this operator is correctly called "the conditional operator". It happens to be a ternary operator, meaning that it is an operator which takes three parameters. ere It runs:
- Unary
- Binary
- Ternary
- Quaternary
etc.
There happens to be only a single ternary operator in C# at present - the conditional operator. There happen to be no quaternary or higher-order operators.
来源:https://stackoverflow.com/questions/20258975/using-ternary-operator-on-console-writeline