简体   繁体   English

c#datarow比较DateTime的DBNull.Value和string的null

[英]c# datarow comparing DBNull.Value for DateTime vs null for string

I have the following code that seems to work: 我有以下代码似乎工作:

DataRow row = <result of a query>;
string strVarName = (row["VarName"]??"").ToString();

I can also use something like this - and it also works: 我也可以使用这样的东西 - 它也有效:

string strVarName = row["VarName"]==null ? "" : row["VarName"].ToString();

I would like to use the same form to get a date. 我想使用相同的表格来获取日期。 Intellisense informs me that the nullable operator does not like working with dates, so I am trying something similar, I have to make Intellisense告诉我可空操作员不喜欢使用日期,所以我尝试类似的东西,我必须做

string strVarName = row["VarName"]==DBnull.Value ? "" : row["VarName"].ToShortDateString();

Get that? 懂吗? For strings I compare to null, but for dates I compare to DBnull. 对于字符串我比较为null,但是对于日期我比较DBnull。 The date string will not work consistently with a comparison to null. 通过与null的比较,日期字符串将无法一致地工作。 I'm okay with this ... and it may be that the string comparison would work if I tried to compare it to DBNull.Value . 我没关系...如果我试图将它与DBNull.Value进行比较,那么字符串比较可能会有效。 I'm just curious why it seems I must use DBNull.Value when comparing to a DateTime field of a DataRow, whereas I may use null when comparing to a string field. 我只是好奇为什么在比较DataRow的DateTime字段时我必须使用DBNull.Value,而在与字符串字段比较时我可能使用null。

DateTime是一个值类型,不能为null,因此您无法将其与null进行比较(就像您无法将int与null进行比较)。

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

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