代码之家  ›  专栏  ›  技术社区  ›  Dib

可以不分配任何内容和/或DBNull的自定义结构?

  •  0
  • Dib  · 技术社区  · 15 年前

    请谁能告诉我,如果有可能贴花一个自定义结构,不能分配任何东西和/或DbNull.值,也可以被实例化为无?

    提前谢谢。

    顺致敬意, 杜安

    2 回复  |  直到 15 年前
        1
  •  2
  •   Dan Tao    15 年前

    好像 Nullable<DateTime> DateTime? 简而言之,或者 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;
    
        2
  •  0
  •   jeroenh    15 年前

    DataRow extension methods . 这些允许您使用可为null的类型,而不再担心DBNull。

    E、 g.假设“MyDateField”字段(DateTime类型)可以为null。然后你可以这样做:

    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);
    }