C# 在强制转换从SqlDataReader返回的可为null的datetime时,指定的强制转换无效

C# 在强制转换从SqlDataReader返回的可为null的datetime时,指定的强制转换无效,c#,datetime,casting,sqldatareader,C#,Datetime,Casting,Sqldatareader,注意:这不是的副本,因为我特别希望避免使用列索引 我有以下目标 public class MyClass { public int ID { get; set; } public DateTime? Deleted { get; set; } } 下面的代码用于从数据库中提取所述对象 MyClass c = new MyClass(); using (SqlConnection conn = new SqlConnection()) { conn.Connection

注意:这不是的副本,因为我特别希望避免使用列索引

我有以下目标

public class MyClass 
{
    public int ID { get; set; }
    public DateTime? Deleted { get; set; }
}
下面的代码用于从数据库中提取所述对象

MyClass c = new MyClass();
using (SqlConnection conn = new SqlConnection())
{
    conn.ConnectionString = "MyConnectionString";
    SqlCommand cmd = new SqlCommand("SELECT ID,Deleted FROM MyTable", conn);
    conn.Open();
    SqlDataReader sdr = cmd.ExecuteReader();
    if (sdr != null && sdr.HasRows)
    {
        while (sdr.Read())
        {
            c.CampID = (int)sdr["ID"];
            c.Deleted = (DateTime?)sdr["Deleted"];
        }
        sdr.Close();
    }
    conn.Close();
}
return c;
如果删除的日期为空,我会得到一个错误

指定的强制转换无效

我做错了什么?如何以这种方式强制转换可为空的datetime字段

我有两个难看的黑客可以完成这项工作。这:

try{
    c.Deleted = (DateTime?)sdr["Deleted"];
}
catch{
    // ignoring a catch makes me feel unclean
}
还是这个

if(!string.isNullOrEmpty(sdr["Deleted"].ToString()))
{
    // not quite so bad, but still not very elegant
    c.Deleted = (DateTime?)sdr["Deleted"];
}
有没有更干净、更优雅的方法

注意:我不想使用字段索引,即

sdr.GetDateTime(i); 
希望这是有帮助的

c.Deleted = sdr["Deleted"] == DBNull.Value ? 
                  (DateTime?)null : Convert.ToDateTime(sdr["Deleted"]); 
测试这一点:

c.Deleted = sdr["Deleted"] as DateTime?;

DBNull.Value
的检查本身是正确和清晰的,但是如果已知该值是
DateTime
,为什么要使用
Convert.ToDateTime
?我不是说这是错误的,我是说这个答案可以从解释中受益,而不仅仅是代码。为什么默认为原始代码返回
null
时的当前时间?为什么不将
作为DateTime?
?这甚至不应该编译。