Nic*_*tch 154 c# generics nullable conditional-operator
有人可以解释为什么这在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'之间没有隐式转换."
并不是说我不能使用前者,但第二种风格与我的其余代码更加一致.
Ste*_*son 322
这个问题已经被问过很多次了.编译器告诉你它不知道如何转换null为DateTime.
解决方案很简单:
DateTime? foo;
foo = true ? (DateTime?)null : new DateTime(0);
Run Code Online (Sandbox Code Playgroud)
请注意,Nullable<DateTime>可以写入DateTime?,这将节省您一堆打字.
Fly*_*wat 19
FYI(Offtopic,但很漂亮并且与可空类型有关)我们有一个方便的运算符,仅用于可空类型,称为空合并运算符
??
Run Code Online (Sandbox Code Playgroud)
像这样使用:
// Left hand is the nullable type, righthand is default if the type is null.
Nullable<DateTime> foo;
DateTime value = foo ?? new DateTime(0);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55079 次 |
| 最近记录: |