从 double 中减去 int 会导致错误

Subtracting int from double leads to an error

我有一个 int 和一个 double,但是当我尝试从 double 中减去整数时,就会抛出以下错误:

Input string was not in a correct format.

现在让我们看一下代码:

double TotalNoRegis = values.Sum(); // This is a LIST and its = 1569
string otherFe ="600";
double totalafter;
if(otherFe != string.Empty || otherFe!= "") // This part works fine
{
    totalafter =  TotalNoRegis - Convert.ToInt32(otherFe); // Here the error is thrown
}

我在这里做错了什么?我查看了这个 Example,这基本上是同一件事:int x = 1int y = 2 然后是 int this = x-y;

如果您知道这里的问题,请告诉我。

您应该使用整数而不是双精度数,尤其是当您没有理由使用双精度数时。因此,要纠正,您只需执行以下操作即可。

int total = values.Sum();
var other = "6000";

if(!string.IsNullOrEmpty(other))
     if(int.TryParse(other, out int subtractor))
          total -= subtractor;

如果你需要双人间,那就用吧,如果你不需要,那又何必呢?此外,您从六千项中减去一千五百项,您的总和将始终为负数或经常为负数。这是您想要的意图吗?

需要注意的一点是,如果 TryParse 失败,它将跳过减法,而不是像解析或转换那样失败。您还想要列表或计数的总和吗?

What am I doing wrong here?

很多。

if(otherFe != string.Empty || otherFe!= "") // This part works fine

这是无意义的代码。 string.Empty"" 相同的字符串 .

改为使用

if (!string.IsNullOrEmpty(otherFe))

继续:

totalafter =  TotalNoRegis - Convert.ToInt32(otherFe); // Here the error is thrown

你说错误是减法,其实不是。问题出在 ToInt32。您传递的字符串与您显示的字符串不同。

我喜欢这样做的方式是制作一个扩展方法:

static public class Extensions 
{
    public static int? ParseAsInteger(this string s) {
        if (string.IsNullOrEmpty(s)) return null;
        int i;
        return int.TryParse(s, out i) ? (int?)i : (int?)null;
    }
    // Similarly write `ParseAsDouble` and so on.
}

现在您有了可以使用的扩展程序:

double? totalAfter = TotalNoRegis - otherFe.ParseAsInteger();

(或 ParseAsDouble,或其他。)

如果 otherFe 有效,则 totalAfter 有总数;如果不是,则为 null.

这里的教训是:将类型转换逻辑移到它自己的方法中,您可以独立测试。然后,该方法调用点的逻辑变得更简单,更容易理解。