static void Main()
{
short x = 3;/* no need explicit casting (short)3 */
Console.WriteLine(Factorial(x));
}
static short Factorial(short x)
{
return x == 0 ?
(short)1 /* need explicit casting (short)1 */
:
(short)(x * Factorial((short)(x - 1)));
}
为什么我需要为三元运算符中的整数文字显式转换为 short
?
最佳答案
(bool) 的类型? (short) : (int)
表达式是 int
,即使 (int)
子表达式是常量并且在 short< 的范围内
.
有一个特殊的异常(exception),当 int
为常量且在范围内时,它可以隐式转换为 short
,但您的完整表达式不是常量,因此该异常不会'适用,并且语言设计者从未添加其他类似的异常,可能是因为它们很少有用。
关于c# - 为什么我需要显式转换来缩短三元运算符中的整数文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22115204/