[英]Custom Structure that can be assigned Nothing and/or DBNull?
请问有人可以给我一个建议,如果可以对一个自定义结构进行除标,该自定义结构可以被分配为Nothing和/或DbNull.Values,并且可以被实例化为Nothing?
我想要做的是创建一个自定义DateTime对象,该对象可以从数据库查询中接收DBNull.Value并以Nothing的身份开始生活。 这可能吗?
提前致谢。
最好的问候,杜安
好像Nullable<DateTime>
(简称DateTime?
或VB.NET中的Date?
) 几乎可以带您到达那里。 您只需要自己专门处理与DBNull
的转换。
// You can set a DateTime? to null.
DateTime? d = null;
// You can also set it to a DateTime.
d = DateTime.Now;
// You can check whether it's null in one of two ways:
if (d == null || !d.HasValue) // (These mean the same thing.)
{ }
// Boxing a DateTime? will either result in null or a DateTime value.
SetDatabaseValue(d);
// As for conversions from DBNull, you'll have to deal with that yourself:
object value = GetDatabaseValue();
d = value is DBNull ? null : (DateTime?)value;
如果使用的是DataSet,请使用Field和SetField DataRow扩展方法 。 这些使您可以使用Nullable类型,而不必再担心DBNull。
例如,假设“ MyDateField”字段(日期时间类型)是可为空的。 然后你可以做这样的事情:
foreach (var row in myDataTable)
{
// will return null if the field is DbNull
var currentValue = row.Field<DateTime?>("MyDateField");
// will set the value to DbNull.Value
row.SetField<DateTime?>("MyDateField", null);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.