问题
Possible Duplicate:
Conditional operator cannot cast implicitly?
When writing a statement using the conditional operator, if the either of the expressions are numeric values they are always interpreted as int
type. This makes a cast necessary to assign a short
variable using this operator.
bool isTrue = true;
int intVal = isTrue ? 1 : 2;
short shortVal = isTrue ? 1 : 2; // Compile error: Cannot implicitly convert type 'int' to 'short'.
Shouldn't the compiler be able to know that both values are valid short
values just as it would in a typical assignment statement(short shortVal = 1;
)?
回答1:
It's not that the conditional operator (AKA ternary operator) always returns ints, it's because your literals are ints.
Unfortunately, C# doesn't appear to have a literal specifier for bytes or shorts (they do for longs, though).
回答2:
This is because your 1 and 2 are int
s. ?:
returns the same type as 2nd and 3rd operands in your case.
Edit: At my VS2008 this works:
short x = true ? 1 : 2;
Did I do something wrong?
Edit: Indeed, the difference was that true
was a compile-time constant. For non-constant expressions I got the same error message.
来源:https://stackoverflow.com/questions/2356618/why-does-the-conditional-operator-always-return-an-int-in-c