我有一个应用程序循环通过固定宽度的文本文件,将每一行读入一个字符串变量并使用.Substring()方法查找给定字段的数据。对于给定的字段,它检查内容是否只是空格,或者其中是否存在实际的“数据”,即除了空格之外的任何内容。例如,如果存在数据,并且该数据表示日期,则对该数据运行DateTime.Parse()并将其传递到C#DataTable中的datetime类型的字段;但是,如果没有数据 - 只是空格,我想简单地将空值传递给该字段。以下是一段代码说明:
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'
)
我在这里缺少什么?
答案 0 :(得分:35)
您需要将DateTime
强制转换为object
才能在条件中使用它:
dr["Application_Date"] = (...) ? (object)DateTime.Parse(...) : DBNull.Value;
答案 1 :(得分:2)
使用null运算符:
dr["Application_Date"] = (object)nullableDateTime ?? DBNull.Value;