繁体   English   中英

C#中可为空的DateTime

[英]Nullable DateTime in C#

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

DateTime? y = 1 == 1 ? null: DateTime.MaxValue;
DateTime? y = null; // assignment works as expected
  • 为什么第一次分配会在nullDateTime?之间产生类型转换错误DateTime?
  • 哪种方式首选的DateTime?空分配DateTime? 在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; DateTime? y = null; 只是将null分配给可为空的对象。

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

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

A1。 因为在三元运算符中,两个表达式/结果都应为同一类型。

累积 到MSDN Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

在您的问题中, nullDateTime.MinValue不匹配,因此conversion between null and DateTime进行错误conversion between null and DateTime

你可以做

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

这样,两个答案都将返回类型为DateTime?的答案DateTime?

A2。 通常,没有分配这种/首选方法。 这取决于用户惯例。 这三个都很好,并且取决于用户要求。

因为?:运算运算符期望两侧都相同。

first_expression和second_expression的类型必须相同,或者必须存在从一种类型到另一种类型的隐式转换。

因此解决方案将如下所示:

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

对于第二个问题,这将是空分配的好方法

DateTime? x = null;

约会时间? y = 1 == 1? null:DateTime.MaxValue;

该语句给出赋值错误的原因不是因为对变量的空赋值,而是因为在三元运算符中使用了空赋值,并且当您在此处使用类类型时,三元运算符不会导致您按照以下方式进行此非法操作提到了CLR规范,它可能会给您带来直接的编译错误。

//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

根据提供的规范和指南,在任何情况下都不应该为类类型分配空值,因此,按照标准,您可以使用最小值(尽管您也可以使用默认值,但是在需要时可能会影响类型转换)

您提到的第二个。 您需要在Nikhil Agrawal爵士所推荐的这段时间内强制转换为空值。

三元

  int y = 1;
  DateTime? dt3 = y == 1 ? (DateTime?)null : DateTime.MinValue;

传统方式

       DateTime? dt3 = null;

        if (y == 1)            
             dt3 = null;            
        else
            dt3 = DateTime.MinValue;

如果要将null转换为可为null的日期时间,则可以使用

DateTime? dt = (DateTime?)null;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM