简体   繁体   中英

using Nullable DateTime in C#

I wanted to assign null value to DateTime type in c#, so I used:

public DateTime? LockTime;

When LockTime is not assigned LockTime.Value contains null by default. I want to be able to change LockTime.Value to null after it has been assigned other value.

您可以直接为变量赋值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.

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.

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. What you can do is to assign null to the LockTime field:

LockTime = null;

However, this will create a new DateTime? instance, so any other pieces of code having a reference to the original LockTime instance will not see this change. 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? 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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