5

我在下面的代码片段中总结了我的问题

struct Point
{
    public int X;
    public int Y;

    public Point(int x, int y)
    {
        this.X = x;
        this.Y = y;
    }

    public override int GetHashCode()
    {
        return base.GetHashCode();
    }

    public void PrintValue()
    {
        Console.WriteLine(
            "{0},{1}",
            this.X, this.Y);
    }
}

上述结构派生自包含 GetHashCode 方法的 ValueType。下面是一个派生自 Object 并包含GetHashCode方法的类版本。

class Point
{
    public int X;
    public int Y;

    public Point(int x, int y)
    {
        this.X = x;
        this.Y = y;
    }

    public override int GetHashCode()
    {
        return base.GetHashCode();
    }

    public void PrintValue()
    {
        Console.WriteLine(
            "{0},{1}",
            this.X, this.Y);
    }
}

我只是想知道。这些实现之间有什么区别吗?

4

1 回答 1

6

Yes; value-types (structs) by default make their hash-code as a composite of the values of their fields. You can observe this by trying:

var s = new Point(1,2); // struct
Console.WriteLine(s.GetHashCode());
s.X = 22; // <=============== struct fields should usually be readonly!
Console.WriteLine(s.GetHashCode()); // different

Note that Equals obeys similar rules.

By contrast, a reference-type (class) uses, by default, the reference itself for both GetHashCode() and Equals(). The s.X = 22 will not impact a class:

var s = new Point(1,2); // class
Console.WriteLine(s.GetHashCode());
s.X = 22;
Console.WriteLine(s.GetHashCode()); // same
于 2012-08-29T09:59:18.367 回答