c# - 如何在 dotnet 中将 ""解析为 long ("0")

给定以下代码:

string example = "1234";
long parsed_example = long.Parse(example);
Console.Writeline(parsed_example);
# => 1234

效果很好。

下面的例子没有:

string example = "";
long parsed_example = long.Parse(example);
# [System.FormatException: Input string was not in a correct format.]

然而目标是:

string example = "";
if (example == "")
{
    example = "0";
}
long parsed_example = long.Parse(example);
Console.Writeline(parsed_example);
# => 0

是否有更短、更合适的解决方案?上面的代码几乎可以证明一个小函数是合理的,我最好有一个内联解决方案。也许是这样的(伪代码):

string example = "";
long parsed_example = example ?? 0, long.Parse(example);

最佳答案

long parsed_example = example == "" ? 0 : long.Parse(example);

但是:不要沉迷于单行解决方案;多行解决方案通常更具可读性和正确性。创建复杂代码没有奖励。您可能还希望查看 string.IsNullOrWhiteSpacelong.TryParse 等。例如:

long value;
if (string.IsNullOrWhiteSpace(example))
{
    // what you want to do with blank/empty values
    value = 42;
}
else if (!long.TryParse(example, out value))
{
    // what you want to do with non-integer values 
   value = 84;
}

关于c# - 如何在 dotnet 中将 ""解析为 long ("0"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69432192/

相关文章:

next.js - Next JS 中的 Font Awesome 6(测试版)和动态图标名称

python - 使用 matplotlib 3.3+ 更改颜色条限制以更改比例

php - 我们在 PHP 数组中称这个符号 => 什么?

go - panic : errors: *target must be interface or

list - Groovy:比较列表忽略其中元素的顺序

arrays - 当我尝试初始化 100 个元素的一维数组并使用指针填充它时出现段错误(核心已转储)

python - Pytorch 与转置之间的不同输出

c - 为什么这种 strcpy 的使用被认为是错误的?

reactjs - 路由在 webpack + react 项目中不起作用

c++ - C++ 中具有不同数据成员的模板结构