问题
I dont understand why is this printing char data type once as char, other time as integer
static void Main(string[] args)
{
char x = 'A';
int i = 0;
Console.WriteLine(x); // A
Console.WriteLine(true ? x : 0); // 65 ???
Console.WriteLine(false ? i : x); // 65 ???
Console.ReadLine();
}
I would expect output to be A, A, A
but the output of above is A, 65, 65
. Why?
回答1:
The ternary/conditional operator ?
requires all of the following three operands:
- An expression that evaluates to a boolean
- An expression that returns a value of any type
- An expression that returns a value of the same type as #2
The return value will always be of the same type; that is why #2 and #3 must be the same type.
If the third operand isn't the same type as the second operand, the compiler will look for an implicit cast and use it if possible.
So when you write
var x = flag ? 65 : 'A';
it is exactly the same as
int x = flag ? (int)65 : (int)'A';
...and will always return an int
.
If this were not the case, the result of the ?
could not be assigned to a strongly typed variable, which would be a serious obstacle.
Also, you cannot write something like this:
var x = flag ? 65 : "A"; //Notice it's a string and not a char
...because there is no implicit cast from "A" to integer.
来源:https://stackoverflow.com/questions/48351313/c-sharp-console-writeline-prints-a-char-type-as-integer