簡體   English   中英

可以分配的自定義結構什么都沒有和/或沒有DBNull?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM