有人可以解释为什么这在C#.NET 2.0中有效:
Nullable<DateTime> foo;
if (true)
foo = null;
else
foo = new DateTime(0);
Run Code Online (Sandbox Code Playgroud)
......但这不是:
Nullable<DateTime> foo;
foo = true ? null : new DateTime(0);
Run Code Online (Sandbox Code Playgroud)
后一种形式给我一个编译错误"无法确定条件表达式的类型,因为'<null>'和'System.DateTime'之间没有隐式转换."
并不是说我不能使用前者,但第二种风格与我的其余代码更加一致.
以下代码将无法编译:
string foo = "bar";
Object o = foo == null ? DBNull.Value : foo;
Run Code Online (Sandbox Code Playgroud)
我得到:错误1无法确定条件表达式的类型,因为'System.DBNull'和'string'之间没有隐式转换
要解决这个问题,我必须做这样的事情:
string foo = "bar";
Object o = foo == null ? DBNull.Value : (Object)foo;
Run Code Online (Sandbox Code Playgroud)
这个演员似乎毫无意义,因为这肯定是合法的:
string foo = "bar";
Object o = foo == null ? "gork" : foo;
Run Code Online (Sandbox Code Playgroud)
在我看来,当三元分支具有不同类型时,编译器不会将值自动提供给类型对象...但是当它们属于相同类型时,则自动装箱是自动的.
在我看来,第一个声明应该是合法的......
任何人都可以描述为什么编译器不允许这样做以及为什么C#的设计者选择这样做?我相信这在Java中是合法的......虽然我没有验证这一点.
谢谢.
编辑:我要求理解为什么Java和C#以不同的方式处理这个问题,C#中的场景下发生了什么使得它无效.我知道如何使用三元,而不是寻找一个"更好的方法"来编写示例代码.我理解C#中的三元规则,但我想知道为什么......
编辑(Jon Skeet):删除了"autoboxing"标签,因为这个问题没有涉及拳击.