給出以下代碼:
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);
uj5u.com熱心網友回復:
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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/314423.html
上一篇:將每個引數轉換為查詢陳述句的問號
下一篇:Rvest無法識別表格
