NUnit 从 ReSharper 与 Visual Studio 2013 获取不同的哈希码值

NUnit Gets Different Hash Code Values from ReSharper vs Visual Studio 2013

根据 Jon Skeet 的回答 here,我在 C# 中有一个相当简单的 GetHashCode() 实现。这是我的代码:

public override int GetHashCode()
{
    unchecked
    {
        int hash = 17;
        if (Title != null)
        {
            hash = hash * 23 + Title.GetHashCode(); // Title is of type string
        }
        return hash;
    }
}

当我通过 Visual Studio 2013 年的 Test Explorer 运行针对此方法的 NUnit 测试时,我得到一个哈希码值,当我通过 ReSharper 8 运行它时 Unit Test Explorer 我得到了不同的值。

这是我的单元测试代码:

[Test]
public void GetGetHashCode_WithLinkAndTitle()
{
    const int expected = -1272954771;
    var target = new Article
    {
        Title = "Rumble News"
    };
    var actual = target.GetHashCode();
    Assert.AreEqual(expected, actual);
}

从 VS 2013 我得到实际 == -1411317427,从 ReSharper 我得到实际 == -1272954771。

为什么从 GetHasCode() 返回的值在不同的测试运行程序中不同,我怎样才能使它们彼此一致?

您可能在一个测试运行器中使用 32 位 CLR,在另一个测试运行器中使用 64 位 CLR。 string.GetHashCode 的实现在两者之间是不同的。您应该依赖它们在运行之间保持一致——它们只需要在单个进程中保持一致。

(对于 GetHashCode 方法来说,从在 class 初始化时 运行domly 初始化的静态字段中获取种子是完全合理的。所以每次你 运行 可执行文件你会得到一组不同的哈希码 - 但它们在单个应用程序域中仍然是一致的。)