gpt4 book ai didi

c# - Object 和 ValueType 类中实现的 GetHashCode 有什么区别?

转载 作者:太空狗 更新时间:2023-10-29 23:09:24 26 4
gpt4 key购买 nike

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

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);
}
}

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

最佳答案

是的;默认情况下,值类型 (structs) 将其哈希码作为其字段值的组合。您可以通过尝试观察这一点:

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

请注意,Equals 遵循类似的规则。

相比之下,引用类型()默认使用引用本身 GetHashCode()等于()s.X = 22不会影响:

var s = new Point(1,2); // class
Console.WriteLine(s.GetHashCode());
s.X = 22;
Console.WriteLine(s.GetHashCode()); // same

关于c# - Object 和 ValueType 类中实现的 GetHashCode 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12175289/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com