处理的DBNull在C# [英] Handle DBNull in C#

查看:95
本文介绍了处理的DBNull在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有更好/更清洁的方式做到这一点?

  INT stockvalue = 0;
如果(!Convert.IsDBNull(读卡器[StockValue]))
    stockvalue =(INT)阅读器[StockValue];


解决方案

最短的(恕我直言)是:

  INT stockvalue =(读卡器[StockValue]为int?)? 0;

说明:


  • 如果阅读器[StockValue] 的类型为 INT 后,该值将返回,而??运营商将返回结果

  • 如果阅读器[StockValue] 的类型是不是 INT (例如DBNull的),则返回null,而??操作者将返回值0(零)。

Is there a better/cleaner way to do this?

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

解决方案

The shortest (IMHO) is:

int stockvalue = (reader["StockValue"] as int?) ?? 0;

Explanation:

  • If reader["StockValue"] is of type int, the value will be returned, and the "??" operator will return the result
  • If reader["StockValue"] is NOT of type int (e.g. DBNull), null will be returned, and the "??" operator will return the value 0 (zero).

这篇关于处理的DBNull在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆