简体   繁体   English

在C#中使用Nullable DateTime

[英]using Nullable DateTime in C#

I wanted to assign null value to DateTime type in c#, so I used: 我想在c#中为DateTime类型赋值null,所以我使用了:

public DateTime? LockTime;

When LockTime is not assigned LockTime.Value contains null by default. 未分配LockTime时LockTime.Value默认包含null。 I want to be able to change LockTime.Value to null after it has been assigned other value. 我希望能够在为其分配其他值后将LockTime.Value更改为null。

您可以直接为变量赋值nullValue属性是只读的,不能赋值):

LockTime = null;

No, if LockTime hasn't been assigned a value, it will be the nullable value by default - so LockTime.Value will throw an exception if you try to access it. 不,如果没有为LockTime分配值,默认情况下它将是可空值 - 因此如果您尝试访问它, LockTime.Value将抛出异常。

You can't assign null to LockTime.Value itself, firstly because it's read-only and secondly because the type of LockTime.Value is the non-nullable DateTime type. 你不能将null LockTime.Value本身,首先是因为它是只读的,其次是因为LockTime.Value的类型是不可为空的 DateTime类型。

However, you can set the value of the variable to be the null value in several different ways: 但是,您可以通过几种不同的方式将变量的值设置为空值:

LockTime = null; // Probably the most idiomatic way
LockTime = new DateTime?();
LockTime = default(DateTime?);

你试过LockTime = null吗?

The Value porperty is readonly, so you can't assign a value to it. Value porperty是readonly,因此您无法为其赋值。 What you can do is to assign null to the LockTime field: 可以做的是为LockTime字段赋值:

LockTime = null;

However, this will create a new DateTime? 但是,这会创建一个新的DateTime? instance, so any other pieces of code having a reference to the original LockTime instance will not see this change. 实例,因此任何其他引用原始LockTime实例的代码都不会看到此更改。 This is nothing strange, it's the same thing that would happen with a regular DateTime , so it's just something your code has to deal with gracefully. 这并不奇怪,它与常规DateTime会发生同样的事情,因此它只是您的代码必须优雅处理的事情。

     DateTime? nullableDT = null;
     Console.WriteLine("{0}\t{1}", nullableDT.HasValue, nullableDT);
     nullableDT = DateTime.Now;
     Console.WriteLine("{0}\t{1}", nullableDT.HasValue, nullableDT);
     nullableDT = null;
     Console.WriteLine("{0}\t{1}", nullableDT.HasValue, nullableDT);
     /*
     False
     True    30.07.2010 11:17:59
     False
     */

You can define the variable this way: 您可以这样定义变量:

private Nullable<DateTime> _assignedDate;  
_assignedDate = DateTime.Now;

and then assign a null value: 然后分配一个空值:

_assignedDate = null;

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

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