Gethashcode() 函数
为什么 C1 和 c2 的哈希码不相同? 代码没有达到“相同”....(两个类中 i=0)
class myclass
{
public static int i;
static void Main()
{
myclass c1 = new myclass();
myclass c2 = new myclass();
if (c1.GetHashCode() == c2.GetHashCode())
Console.Write("Same");
}
}
Why aren't C1 and c2 have the same hashcode ?
the code doesn't get to "Same".... ( i=0 in both classes)
class myclass
{
public static int i;
static void Main()
{
myclass c1 = new myclass();
myclass c2 = new myclass();
if (c1.GetHashCode() == c2.GetHashCode())
Console.Write("Same");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
GetHashCode()
的默认实现基于引用,而不是对象的字段。如果您希望它们相同,则需要覆盖
GetHashCode()
,因此它基于您的字段(然后您应该记住也覆盖Equals()
)。The default implementation of
GetHashCode()
is based on the reference, not the fields of the object.If you want them to be the same, you need to override
GetHashCode()
, so it is based on your field (and then you should remember to overrideEquals()
also).因为您正在创建同一类的不同实例。类的每个实例都有自己的哈希码,哈希码用于标识程序内存中的对象,即使它们共享相同的字段值。
但是,如果您这样做,它会写为“Same”,因为您只是创建了两个指向同一个对象的变量(即您将
c1
的引用传递给该对象c2
):当然,我认为这不是您想要实现的目标。
Because you're creating different instances of the same class. Each instance of a class has its own hashcode, and the hashcode is used to identify an object in your program's memory, even if they both share the same field values.
If you did this, however, it'll write "Same", because you're just creating two variables that point to the same object (i.e. you're passing the reference of
c1
to the object toc2
):Of course, I don't think this is what you're looking to achieve.