i have an existing DateTime? object that has a datetime in i开发者_开发技巧t. I want to remove the datetime value from it so when you ask "HasValue" it returns false?
Nullable<T>
is immutable, so you will have to reassign the variable to a different value to be able to change / remove the underlying value. This makes sense since it is a value-type (although a special one at that); value-types are normally immutable in the framework. You will notice that neither theValue
nor theHasValue
property forNullable<T>
has a setter.
DateTime? nullableDt = DateTime.Now;
Console.WriteLine(nullableDt.HasValue); //true
nullableDt = null;
Console.WriteLine(nullableDt.HasValue); //false
or
nullableDt = new DateTime?();
Set it to null.
If you have
DateTime? value = DateTime.Now;
then call
value = null;
Why not just set it back to null?
DateTime? d = null;
System.Diagnostics.Debug.WriteLine("HasValue1 = {0}", d.HasValue); //False
d = DateTime.Now;
System.Diagnostics.Debug.WriteLine("HasValue2 = {0}", d.HasValue); //True
d = null;
System.Diagnostics.Debug.WriteLine("HasValue3 = {0}", d.HasValue); //False
The variable itself cannot be null, though you can set the minValue, it is an equivalent to '1/1/0001 00:00:00'
DateTime dvar = DateTime.MinValue;
精彩评论