有人能解释一下为什么这在C#.NET 2.0中有效:
Nullable<DateTime> foo;
if (true)
foo = null;
else
foo = new DateTime(0);
...but这不是:
Nullable<DateTime> foo;
foo = true ? null : new DateTime(0);
后一种形式给出了一个编译错误:“无法确定条件表达式的类型,因为'‘和’System.DateTime‘之间没有隐式转换。”
并不是说我不能使用前者,而是第二种风格与我的其余代码更一致。
发布于 2008-11-17 15:21:27
编译器告诉您它不知道如何将null
转换为DateTime
。
解决方案很简单:
DateTime? foo;
foo = true ? (DateTime?)null : new DateTime(0);
请注意,可以将Nullable<DateTime>
编写为DateTime?
,这将为您节省大量的输入工作。
发布于 2008-11-17 15:25:49
仅供参考(离题,但很漂亮,与可空类型相关)我们有一个仅用于可空类型的方便的运算符,称为空合并运算符
??
如下所示:
// Left hand is the nullable type, righthand is default if the type is null.
Nullable<DateTime> foo;
DateTime value = foo ?? new DateTime(0);
发布于 2008-11-17 15:22:26
这是因为在三元运算符中,这两个值必须解析为相同的类型。
https://stackoverflow.com/questions/295833
复制相似问题