如何检查DateTime对象是否未分配? [英] How to check if DateTime object was not assigned?

查看:121
本文介绍了如何检查DateTime对象是否未分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,首先。代码:
我有一个类:

  public class Myobject 
{
public string Code {get;组; }
public DateTime? StartDate {get;组; }
}

这是非常简单的源代码的一部分:

  MyObject mo = new MyObject(); 
mo.Code =sth;
//对StartDate属性没有动作!

if(mo.StartDate.HasValue)
{
sc.Parameters.Add(new SqlParameter(@ inStartDate,mo.StartDate.Value));
}
else
{
sc.Parameters.Add(new SqlParameter(@ inStartDate,DBNull.Value));
}

简单的'如果' - Sql Server 2008,抛出一个错误 - 当得到null日期时间(它必须是DBNull.Value)
所以我想先检查它,然后传递正确的值或DBNull。



我的问题是 - 这个'如果'总是retruns true!为什么!?



还尝试了:

  if(mo.StartDate.Value == null)

但它总是返回false。怎么来不是null?甚至没有创建..



所以.. 如何检查DateTime对象是否未分配?

解决方案

尝试这样:

  
if mo.StartDate.GetValueOrDefault()!= DateTime.MinValue)
{
// True - mo.StartDate的值为
}
else
{
// False - mo.StartDate没有值
}


So, First of all. Code: I've got a class:

public class Myobject
{
    public string Code { get; set; }
    public DateTime? StartDate { get; set; }
}

And this is part of very simple source:

MyObject mo = new MyObject();
mo.Code= "sth";
// NO action on StartDate property! 

    if (mo.StartDate.HasValue)
    {
        sc.Parameters.Add(new SqlParameter("@inStartDate", mo.StartDate.Value));
    }
    else
    {
        sc.Parameters.Add(new SqlParameter("@inStartDate", DBNull.Value));
    }

Simple 'if' - Sql Server 2008, throw an error - when gets null Datetime (it has to be DBNull.Value) So I want to check it first, and then pass right value or DBNull.

My problem is - this 'if' always retruns true! Why!?

Also tried that:

if (mo.StartDate.Value == null)

but it always returns false. How come it is not a null? It was not even created..

So.. How to check if DateTime object was not assigned?

解决方案

Try this:


if (mo.StartDate.GetValueOrDefault() != DateTime.MinValue) 
{
  // True - mo.StartDate has value
}
else
{
  // False - mo.StartDate doesn't have value
}

这篇关于如何检查DateTime对象是否未分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆