Handle DBNull in C#

前端 未结 13 785
梦谈多话
梦谈多话 2020-11-30 01:36

Is there a better/cleaner way to do this?

int stockvalue = 0;
if (!Convert.IsDBNull(reader[\"StockValue\"]))
    stockvalue = (int)reader[\"StockValue\"];
         


        
13条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 02:20

    The way I handle this is

    int? stockvalue = reader["StockValue"] as int?;
    

    Very simple, clean and one line. If for some reason I absolutely can't have a null value (which I find poor reasoning for usually since I'd rather know if a value has meaning or if it was unitialized for a primitive type) I would do:

    int stockvalue = (reader["StockValue"] as int?).GetValueOrDefault(-1);
    

提交回复
热议问题