如何在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.IsNullOrWhiteSpace,long.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;
}

最新更新