有谁知道为什么最后一个不起作用?
object nullObj = null;
short works1 = (short) (nullObj ?? (short) 0);
short works2 = (short) (nullObj ?? default(short));
short works3 = 0;
short wontWork = (short) (nullObj ?? 0); //Throws: Specified cast is not valid
有谁知道为什么最后一个不起作用?
object nullObj = null;
short works1 = (short) (nullObj ?? (short) 0);
short works2 = (short) (nullObj ?? default(short));
short works3 = 0;
short wontWork = (short) (nullObj ?? 0); //Throws: Specified cast is not valid
因为0
是一个int,它被隐式转换为一个对象(装箱),并且不能将装箱的int直接拆箱为short。这将起作用:
short s = (short)(int)(nullObj ?? 0);
已装箱T
(T
当然,其中是不可为空的值类型)只能拆箱到T
或T?
。
最后一行中的 null 合并运算符的结果是一个装箱的int
. 然后,您尝试将其拆箱到short
,这在执行时以您显示的方式失败。
就像你已经这样做了:
object x = 0;
short s = (short) x;
null-coalescing 运算符的存在在这里有点红鲱鱼。