简体   繁体   English

可以分配的自定义结构什么都没有和/或没有DBNull?

[英]Custom Structure that can be assigned Nothing and/or DBNull?

Please can any one advise me if it is possible to decalre a custom structure that can be assigned Nothing and / or DbNull.Values, and also can be instanciated as Nothing? 请问有人可以给我一个建议,如果可以对一个自定义结构进行除标,该自定义结构可以被分配为Nothing和/或DbNull.Values,并且可以被实例化为Nothing?

What I am looking to do is ceate a custom DateTime object that can recieve a DBNull.Value from a database query and also start life as Nothing. 我想要做的是创建一个自定义DateTime对象,该对象可以从数据库查询中接收DBNull.Value并以Nothing的身份开始生活。 IS this possible? 这可能吗?

Thanks in advance. 提前致谢。

Best regards, Duane 最好的问候,杜安

Seems like Nullable<DateTime> ( DateTime? for short, or Date? in VB.NET) gets you almost all the way there. 好像Nullable<DateTime> (简称DateTime?或VB.NET中的Date?几乎可以带您到达那里。 You just need to specially deal with the conversion to/from DBNull on your own. 您只需要自己专门处理与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;

If you're working with DataSets, use the Field and SetField DataRow extension methods . 如果使用的是DataSet,请使用Field和SetField DataRow扩展方法 These allow you to use Nullable types without worrying about DBNull anymore. 这些使您可以使用Nullable类型,而不必再担心DBNull。

Eg, suppose the "MyDateField" field (of type DateTime) is nullable. 例如,假设“ MyDateField”字段(日期时间类型)是可为空的。 Then you can do something like this: 然后你可以做这样的事情:

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.

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