如何转换 int32 中的空字符串?

How to convert empty string in int32?

我正在开发从 html table 中获取数据的软件。所以这一行:

team.SelectSingleNode(".//td[@class='number total won total_won']")?.InnerText.Trim();

returns: ""

(我正在使用 html 敏捷包进行 DOM 操作。)

完整的一行是这样的:

Convert.ToInt32(
  team.SelectSingleNode(
    ".//td[@class='number total won total_won']")
  ?.InnerText.Trim());

这returns一个例外(格式不正确例外)。

有什么解决办法吗?

您可以使用 int.TryParse 而不是 Convert.ToInt32

int myInt;
if(!int.TryParse(team.SelectSingleNode(".//td[@class='number total won total_won']")?.InnerText.Trim(), out myInt))
{
  myInt = 0;
}

I know, but I've 30+ lines of code, so I should add a lot of if conditions... – Ilnumerouno just now

您可以改为编写辅助方法。

public static class Converter{
    public static int ConvertToInt(string stringAsInt){
      int myInt;
      return int.TryParse(stringAsInt, out myInt) ? myInt : 0;
    }
}

调用代码。

var parsedInt = Converter.ConvertToInt(team.SelectSingleNode(".//td[@class='number total won total_won']")?.InnerText.Trim());