为什么条件运算符总是返回在C#中一个int? [英] Why does the conditional operator always return an int in C#?
问题描述
可能重复:结果
的有条件的经营者不能隐式转换?
在一份书面陈述使用href=\"http://msdn.microsoft.com/en-us/library/ty67wk28.aspx\" rel=\"nofollow\">条件运算的 INT 类型。这就需要分配使用该运营商短
变量投。
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'.
不应该编译器能够知道这两个值都是有效的短
值,就像它在一个典型的赋值语句(短shortVal = 1;
)?
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和2是 INT
秒。 :
返回相同类型的第二和第三个操作数你的情况
This is because your 1 and 2 are int
s. ?:
returns the same type as 2nd and 3rd operands in your case.
编辑:在我的VS2008这个作品:
At my VS2008 this works:
short x = true ? 1 : 2;
难道我做错了什么?
Did I do something wrong?
编辑:的确,不同的是,真正
是一个编译时间常数。对于非常量表达式,我得到了相同的错误消息。
Indeed, the difference was that true
was a compile-time constant. For non-constant expressions I got the same error message.
这篇关于为什么条件运算符总是返回在C#中一个int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!