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

当数据集中的项可能为空时,如何正确地强制转换该项?

  •  4
  • mezoid  · 技术社区  · 16 年前

    我有一个由存储过程返回的数据集,其中的一个项可能为null。我试图将数据集中的每一行转换为强类型对象,但似乎无法正确地转换null值。

    我已经创建了一个场景模型,如下所示:

    DataSet ds = new DataSet();
    ds.Tables.Add(new DataTable());
    ds.Tables[0].Columns.Add("Name", typeof(string));
    ds.Tables[0].Columns.Add("Amount", typeof(decimal));
    ds.Tables[0].Rows.Add("My Name Here", null); //create row with a null item
    
    DataRow dataRow = ds.Tables[0].Rows[0];
    
    Person p = new Person
    { 
        Name = (string)dataRow["Name"], 
        Amount = (decimal)dataRow["Amount"]
    }
    

    不幸的是,我遇到了以下异常: System.InvalidCastException: Specified cast is not valid.

    System.NotSupportedException: DataSet does not support System.Nullable<>.

    dataRow["Amount"] is decimal (false)
    dataRow["Amount"] is decimal? (false)
    dataRow["Amount"] == null (false)
    dataRow["Amount"] is object (true)
    

    3 回复  |  直到 16 年前
        1
  •  6
  •   hvintus    16 年前

    你可以用 dataRow.IsNull("Amount") Convert.IsDBNull(dataRow["Amount"]) (dataRow["Amount"] as Decimal) != null

        2
  •  1
  •   ChrisHDog    16 年前

    您还可以检查数据库是否返回Null,如下所示:

    if (dataRow["Amount"] is System.DBNull.Value)
    

        3
  •  1
  •   James_2195    16 年前

    你试过使用decimal.TryParse吗?

    例如:

    decimal result;
    
    if (decimal.TryParse(dataRow["Amount"].ToString(), out result))
    {
    //do something
    }