C#中可为空的DateTime [英] Nullable DateTime in C#

查看:157
本文介绍了C#中可为空的DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个有关DateTime评估的问题

I have two questions related to DateTime assingments

DateTime? y = 1 == 1 ? null: DateTime.MaxValue;
DateTime? y = null; // assignment works as expected

  • 为什么第一次分配在 null DateTime之间产生类型转换错误?
  • 在c#中对 DateTime?进行空赋值的首选方法是哪种?

    • Why the first assignment issues error of type conversion between null and DateTime?
    • Which is the preferred way for null assignments of DateTime? in c#.

      DateTime? x = default(DateTime?); //prints null on console
      
      DateTime? x = null;               // prints null on console
      
      DateTime? x = DateTime.MinValue;  //print 01/01/0001 
      

    • 推荐答案

      第二条语句 DateTime?y = null; 只是将null分配给可为空的对象.

      The second statement DateTime? y = null; is only an assignment of null to a nullable object.

      第一个是条件赋值,它为真实状态赋值,为假赋值;在这里,您使用条件运算符来评估条件.根据 MSDN first_expression (如果为true,则执行) second_expression * (如果为false,则执行)*必须是同一类型,或者必须存在从一种类型到另一种类型的隐式转换.在我们的情况下,两者是不同的,因此简单的解决方案是像这样进行显式转换:

      Whereas the first is a conditional assignment, which assigns some value for the true state and some other value for the false; Here you are using the conditional operator for evaluating the condition. according to MSDN first_expression (executes if true) and second_expression*(executes if false)* must be of same type or an implicit conversion must exist from one type to the other. In our case both are different so The simple solution is doing an explicit conversion as like this:

      DateTime? y = 1 == 1 ?(DateTime?) null : DateTime.MaxValue;
      

      这篇关于C#中可为空的DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆