给定指定强制转换的空合并运算符无效

Mat*_*rla 10 .net c# casting null-coalescing-operator

有谁知道为什么最后一个不起作用?

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
Run Code Online (Sandbox Code Playgroud)

pho*_*oog 15

因为0是一个int,它被隐式转换为一个对象(盒装),并且你不能将一个盒装的int直接解包为short.这将有效:

short s = (short)(int)(nullObj ?? 0);
Run Code Online (Sandbox Code Playgroud)

盒装T(T当然是不可为空的值类型)可以仅取消装箱T或取消装箱T?.

  • [Representation and Identity](http://blogs.msdn.com/b/ericlippert/archive/2009/03/19/representation-and-identity.aspx)解释了为什么这是必要的(即为什么不这样做)自动只有1个演员). (2认同)

Jon*_*eet 5

最后一行中的null-coalescing运算符的结果是一个盒装的int.然后你试图将其拆箱,short在执行时以你显示的方式失败.

就像你这样做了:

object x = 0;
short s = (short) x;
Run Code Online (Sandbox Code Playgroud)

null-corangecing运算符的存在在这里有点像红鲱鱼.