在 .NET Framework 中,实现 (override) of Equals(object) and GetHashCode()对于浮点类型(System.Double and System.Single) is wrong。引用自MSDN GetHashCode(object)规格 http://msdn.microsoft.com/en-us/library/system.object.gethashcode:
现在,这个错误已经被举报 http://connect.microsoft.com/VisualStudio/feedback/details/648567/在 Microsoft Connect 上。但他们为什么不解决这个问题呢?
解决办法很简单:要么让不同的NaNnot比较相等,或者选择一个固定的哈希码来返回任何NaN.
修复不会破坏任何东西:按照今天的情况,不同时什么都不起作用NaN被使用。
你能想到吗any有理由不解决这个问题吗?
这是一个说明当前行为的简单示例:
using System;
using System.Collections.Generic;
using System.Linq;
static class Program
{
const int setSize = 1000000; // change to higher value if you want to waste even more memory
const double oneNaNToRuleThemAll = double.NaN;
static readonly Random randomNumberGenerator = new Random();
static void Main()
{
var set = new HashSet<double>(); // uses default EqualityComparer<double>
while (set.Count < setSize)
set.Add(GetSomeNaN());
Console.WriteLine("We now have a set with {0:N0} members", set.Count);
bool areAllEqualToTheSame = set.All(oneNaNToRuleThemAll.Equals);
if (areAllEqualToTheSame)
Console.WriteLine("By transitivity, all members of the set are (pairwise) equal.");
}
static double GetSomeNaN() // can also give PositiveInfinity, NegativeInfinity (unlikely)
{
byte[] b = new byte[8];
randomNumberGenerator.NextBytes(b);
b[7] |= 0x7F;
b[6] |= 0xF0;
return BitConverter.ToDouble(b, 0);
}
}
运行代码的结果:a中有100万个重复项HashSet<>.
请注意:这有nothing完全与== and !=C# 的运算符。请用Equals如果你想亲自检查一下。