可以指定 Nothing 和/或 DBNull 的自定义结构?

发布于 2024-09-24 10:32:02 字数 160 浏览 0 评论 0原文

请任何人告诉我是否可以贴花一个可以分配 Nothing 和/或 DbNull.Values 的自定义结构,并且也可以实例化为 Nothing ?

我想要做的是创建一个自定义 DateTime 对象,它可以从数据库查询中接收 DBNull.Value 并且也以 Nothing 开始。这可能吗?

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?

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. IS this possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

坚持沉默 2024-10-01 10:32:02

看起来像 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;

Seems like Nullable<DateTime> (DateTime? for short, or Date? in VB.NET) gets you almost all the way there. You just need to specially deal with the conversion to/from DBNull on your own.

// 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;
我做我的改变 2024-10-01 10:32:02

如果您使用数据集,请使用 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);
}

If you're working with DataSets, use the Field and SetField DataRow extension methods. These allow you to use Nullable types without worrying about DBNull anymore.

E.g., suppose the "MyDateField" field (of type DateTime) is nullable. 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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文