c# - 为什么我需要显式转换来缩短三元运算符中的整数文字?

标签 c# type-conversion

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/

相关文章:

c# - 获取 Autofac 中接口(interface)的所有注册实现

c# - 为什么减去两个本地 DateTime 值似乎不能解释夏令时?

Delphi 支持 SQLite list 类型

c# - 如果元素中存在属性,则将 XAttribute 添加到 XElement

c# - 垃圾收集器将如何处理值类型和引用类型

c# - 一个事件是否需要至少有一个处理程序?

C编程: how to get normal value of int without using value - 48?

c++ - 为什么在完美转发中不允许隐式转换?

c# - 是否有任何通用的 Parse() 函数可以使用解析将字符串转换为任何类型?

c++ - unsigned char* 在 C++ 中加倍