2

在php中我可以做这样的事情:

if (balance == 0 && !neverBought)

其中 balance 来自 API 并且是一个字符串。

在 C# 中,我尝试将 balance 转换为 int,如下所示:

if (int.Parse(balance) == 0 && !(neverBought))

但我得到异常详细信息:System.FormatException:输入字符串的格式不正确。

我究竟做错了什么?

4

2 回答 2

7

If you are not sure if the string is valid use a method such as TryParse to attempt to parse it without throwing an exception:

Based on comments you also don't have an integer, you have a decimal value, so you should parse it as one as well.

decimal decimalBalance;
if(decimal .TryParse(balance, out decimalBalance) 
    && decimalBalance == 0m && !neverBought)
于 2013-10-23T19:48:29.447 回答
-1

如果您确定 balance 不是字符串,Convert.ToInt32() 可能也会有所帮助

            string a = "3";
            int b = 3;
            if (Convert.ToInt32(a) == b)
            {
                //do smth
            }
于 2013-10-24T07:43:02.867 回答