如何抢先尝试将DBNull分配给int? [英] How can I preempt the attempted assignment of DBNull to an int?

查看:135
本文介绍了如何抢先尝试将DBNull分配给int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码:

foreach (DataRow fillRateDataRow in dtFillRateResults.Rows)
{
    . . .
    var frbdbc = new FillRateByDistributorByCustomer
    {
        ShortName = fillRateDataRow["ShortName"].ToString(),
        Unit = fillRateDataRow["Unit"].ToString(),
        CustNumber = fillRateDataRow["Custno"].ToString(),
        MemberItemCode = fillRateDataRow["MemberItemCode"].ToString(),
        Qty = Convert.ToInt32(fillRateDataRow["Qty"]),
        QtyShipped = Convert.ToInt32(fillRateDataRow["QtyShipped"]),
        ShipVariance = fillRateDataRow["ShipVariance"].ToString(),
        CWeek = fillRateDataRow["CWeek"].ToString(),
        PAItemCode = fillRateDataRow["PAItemCode"].ToString(),
        PADescription = fillRateDataRow["PADescription"].ToString(),
        TransactionType = fillRateDataRow["TransactionType"].ToString(),
        SplitCase = fillRateDataRow["SplitCase"].ToString(),
        ReasonCode = fillRateDataRow["ReasonCode"].ToString(),
        ReasonDescription = fillRateDataRow["ReasonDescription"].ToString(),
        CompanyName = fillRateDataRow["CompanyName"].ToString()
    };

...一次失败的原因是, 对象无法从DBNull强制转换
异常来源:mscorlib
异常StackTrace:在System.DBNull.System.IConvertible.ToInt32(IFormatProvider提供程序)在System.Convert.ToInt32(对象值)处的
>

...fails once in a great while with, "Object cannot be cast from DBNull to other types. Exception Source: mscorlib Exception StackTrace: at System.DBNull.System.IConvertible.ToInt32(IFormatProvider provider) at System.Convert.ToInt32(Object value)"

因此,似乎Qty或QtyShipped有时是DBNull(在成串的字符串中唯一的int val)。

So it seems that either Qty or QtyShipped are sometimes DBNull (the only int vals amidst a sea of strings).

是否可以说如果它是DBNull,则将0分配给var,从而避免出现异常?

Is there a way to say "if it's DBNull, assign 0 to the var" and thus avoid the exception?

推荐答案

您可以使用条件表达式:

You can use a conditional expression:

QtyShipped = fillRateDataRow["QtyShipped"] != DBNull.Value ? Convert.ToInt32(fillRateDataRow["QtyShipped"]) : 0

如果需要做很多事情,为此任务创建一个辅助方法将使您可以收缩代码以提高可读性。

If you need to do it a lot, making a helper method for this task would let you shrink your code for better readability.

这篇关于如何抢先尝试将DBNull分配给int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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