gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:30:42 25 4
gpt4 key购买 nike

给定以下代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com