为什么 Assert.AreEqual 只有 double 和 object 的重载

Why Assert.AreEqual has only overloads for double and object

我想比较整数、布尔值、字符串等。出于好奇,为什么 Assert.AreEqual 明确支持双打而不支持其他类型?

我应该怎么做:

var a = 1;
var b = 2;
var areEqual = a == b;
Assert.IsTrue(areEqual);

而不是:

var a = 1;
var b = 2;
Assert.AreEqual(a, b);

编辑澄清:问题是为什么此方法不显式支持其他类型并且仅支持双精度类型。

编辑 2 以进一步说明:这个问题是出于好奇,我没有要解决的问题。

查看确切的方法签名会有所帮助:

Assert.AreEqual(double expected, double actual, double tolerance);
Assert.AreEqual(object expected, object actual);

如您所见,有些“容差”概念显然仅在比较 double 类型时适用。 The documentation实际上直接解决了这一点:

Values of type float and double are compared using an additional argument that indicates a tolerance within which they will be considered as equal.

所以重载是为了处理比较浮点值时的精度问题。这是一个非常有据可查的在线问题。例如,来自 Microsoft 的 here

two apparently equivalent values can be unequal due to the differing precision of the two values [... ] Rather than comparing for equality, one technique involves defining an acceptable relative margin of difference between two values (such as .001% of one of the values)

要比较两个 double 值,您应该这样做:

Assert.AreEqual(0.1 + 0.1 + 0.1, 0.3, 0.00000001);