简体   繁体   English

我如何检查DateTime是否为null

[英]how do i check if DateTime is null

if (string.IsNullOrEmpty(value)) is for string, but what is the code to check if Datetime is null? if(string.IsNullOrEmpty(value))是否用于string,但是检查Datetime是否为null的代码是什么?

    private DateTime? _ReleaseDate;

    public DateTime? ReleaseDate
    {
        get
        {
            return _ReleaseDate;
        }
        set
        {
            if ()
            {

            }
            else
            {
                _ReleaseDate = value;
            }
        }
    }

The ValueType? ValueType? pattern is shorthand for Nullable<ValueType> . pattern是Nullable<ValueType>简写。 In your case you have Nullable<DateTime> . 在您的情况下,您具有Nullable<DateTime>

As you can see from the docs, Nullable<ValueType> implements a HasValue property, so you can simply check it like so: 从文档中可以看到, Nullable<ValueType>实现了HasValue属性,因此您可以像这样简单地检查它:

if (value.HasValue)
{

}
else
{

}

If you simply want to set a default value you can use the GetValueOrDefault method of Nullable<T> and do away with the if statement: 如果只想设置默认值,则可以使用Nullable<T>GetValueOrDefault方法,并取消if语句:

_ReleaseDate = value.GetValueOrDefault(DateTime.MinValue); // or whatever default value you want.

For nullbale types you can use HasValue or != null 对于nullbale类型,可以使用HasValue!= null

However for your example (with the code shown), you have more options 但是,对于您的示例(显示代码),您还有更多选择

public DateTime? ReleaseDate
{
    get
    {
        return _ReleaseDate;
    }
    set
    {
        // if value is null, then that's all good, _ReleaseDate will be null as well
        _ReleaseDate = value; 
    }
}

Or 要么

public DateTime? ReleaseDate {get;set}

The only reason you would need to do something like below, is when you have some specific behaviour on null or otherwise 您需要执行类似以下操作的唯一原因是,当您对null或其他情况有某些特​​定行为时

public DateTime? ReleaseDate
{
    get
    {
        return _ReleaseDate;
    }
    set
    {
        if (value.HasValue)
        {
            // has a value
        }
        else
        {
           // doesnt 
        }
    }
}

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

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