24

我有一个应用程序,它遍历一个固定宽度的文本文件,将每一行读入一个字符串变量,并使用 .Substring() 方法来查找给定字段的数据。对于给定的字段,它会检查内容是否只是空格,或者其中是否实际存在“数据”,即除了空格之外的任何内容。例如,如果有数据,并且该数据表示日期,则 DateTime.Parse() 对该数据运行并传递给 C# DataTable 中日期时间类型的字段;但是,如果没有数据——只有空格,我想简单地将一个空值传递给该字段。下面是一段代码来说明:

var dataTable = new DataTable();

dataTable.Columns.Add("Application_Date").DataType = Type.GetType("System.DateTime");

while (!sr.EndOfStream)
{
    string row = sr.ReadLine();

    if (row.Substring(0, 1) == "2" && row.Substring(42, 1) == "T")
    {
        DataRow dr = dataTable.NewRow();

        dr["Application_Date"] = row.Substring(124, 8) != "        " ?
                                 DateTime.Parse(row.Substring(124, 4) +
                                 "-" + row.Substring(128, 2) + "-" +
                                 row.Substring(130, 2)) :
                                 null as DateTime?;                                                         

     }
}

我的问题是,当我尝试运行它时,它会抛出一个错误,说它想要一个 DBNull ( Cannot set Column 'Application_Date' to be null. Please use DBNull instead.)

但是当我尝试简单地传递一个 DBNull 时,它告诉我它不能在 DateTime 和 DBNull ( Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime?' and 'System.DBNull')之间转换

我在这里想念什么?

4

2 回答 2

46

您需要将DateTimetoobject转换为在条件中使用它:

dr["Application_Date"] = (...) ? (object)DateTime.Parse(...) : DBNull.Value;
于 2011-03-07T18:37:26.363 回答
16

使用空合并运算符:

dr["Application_Date"] = (object)nullableDateTime ?? DBNull.Value;
于 2018-10-05T05:03:54.627 回答