是空检查然后转换为十进制 [英] Is Null Check and Then Convert to decimal

查看:92
本文介绍了是空检查然后转换为十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码在这里..



my code is here..

foreach (DataRow dr in gv1.Rows)
{
    decimal Total_Sqrft = Convert.ToDecimal(
        String.IsNullOrEmpty(Convert.ToString(dr[1])) ?? "0" : Convert.ToString(dr[1])
    );
}





更新:

我解决了它使用..





Updated:
I solved It Using..

if(String.IsNullOrEmpty(Convert.ToString(dr[1])))
{
    decimal Total_Sqrft=0;
}
else
{
    decimal Total_Sqrft = Convert.ToDecimal(dr[1]);
}



但是我想知道上面的操作。


But I want to know about the above operation.

推荐答案

第一件事你需要检查是否 dr [1] 不为空(假设数据表中至少有两列)。

然后你可以使用方法 dr [1] .ToString()转换为字符串。



[更新:也照顾空字符串]

长篇大论方便阅读:

The first thing you need to check is if dr[1] is not null (assuming there are at least two columns in the data table).
Then you can use the method dr[1].ToString() to convert to a string.

[Updated: Also takes care of empty string]
The "long winded" way for easy reading:
decimal Total_Sqrft = 0;
foreach (DataRow dr in gv1.Rows)
{
    Total_Sqrft = 0;
    if (dr[1] != null)
    {
        string tmp = dr[1].ToString();
        if (tmp != String.Empty)
            Total_Sqrft = decimal.Parse(tmp);
    }
}





单行



The one-liner

decimal Total_Sqrft = 0;
foreach (DataRow dr in gv1.Rows)
{
    // The below code can be read:
    // if dr[1] is not null, use the value in the cell otherwise default to 0.
    Total_Sqrft = decimal.Parse((dr[1] == null || dr[1].ToString() == String.Empty) ? "0" : dr[1].ToString());
}





您还可以查看 decimal.TryParse(...)


请不要写这样的代码 - 你必须停下来仔细查看它才能弄清楚发生了什么。如果它会像那样长篇大论。



但是......冒号在那里做什么?

空合并运算符??只需要两个参数 - 一个在左边,一个在右边。

你是否混淆了条件运算符?:?
Please, don't write code like that - you have to stop and look at it pretty closely in order to work out what is going on. Write it long hand if it's going to be like that.

But...what the heck is that colon doing in there?
The null coalescence operator "??" only takes two parameters - one on the left and one on the right.
Are you confusing this with the conditional operator "?:" ?


添加一个自定义转换功能



Add a custom Function for the conversion

public decimal CnvToDecimal(object Data)
        {
            try
            {
                return System.Convert.ToDecimal(Data);
            }
            catch
            {
                return 0;
            }
        }





并调用此功能





and call the function like this

foreach (DataRow dr in gv1.Rows)
           {
               decimal Total_Sqrft = CnvToDecimal(dr[1]);
           }





祝你好运; - )



good luck ;-)


这篇关于是空检查然后转换为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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