如果解析失败,如何使我的十进制变量为 0?

How can I make my decimal variable 0 if the parse fails?

我正在使用 NPOI 库读取 excel 文件,其中一列的价格并不总是设置,当单元格为空时,我的代码崩溃了,所以我想看看如何制作如果单元格为空或解析失败,我的变量 0,以最佳方式为准

我的代码如下

 decimal grossPrice = decimal.Parse(row.GetCell(10).ToString());

使用https://docs.microsoft.com/en-us/dotnet/api/system.decimal.tryparse?view=netframework-4.8

When this method returns, contains the Decimal number that is equivalent to the numeric value contained in s, if the conversion succeeded, or zero if the conversion failed.

decimal grossPrice = 0;
decimal.TryParse(row.GetCell(10).ToString(), out grossPrice);

根据您使用的 C# 版本,您可以使用 TryParse,也可用于 intfloat 等:

decimal grossPrice = decimal.TryParse(row.GetCell(10).ToString(), out var val) ? 
                     val : your_default_value; //your_default_value = 0 in your case

decimal val = 0;
if (decimal.TryParse(row.GetCell(10).ToString(), out val)
{
   //value set
   //not needed, but handy for the completeness of this example
}

else
{
   //value not set (error; assign default value to val)
   //not needed, but handy for the completeness of this example
}