请任何人告诉我是否可以贴一个自定义结构,可以分配 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;
如果您使用数据集,请使用 Field 和 SetField DataRow 扩展方法。这些允许您使用 Nullable 类型而不必再担心 DBNull。
例如,假设“MyDateField”字段(DateTime 类型)可为空。然后你可以做这样的事情:
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);
}