Gethashcode() 函数

发布于 2024-09-16 03:50:15 字数 317 浏览 3 评论 0原文

为什么 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风向决定发型 2024-09-23 03:50:15

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 override Equals() also).

美胚控场 2024-09-23 03:50:15

因为您正在创建同一类的不同实例。类的每个实例都有自己的哈希码,哈希码用于标识程序内存中的对象,即使它们共享相同的字段值。

但是,如果您这样做,它会写为“Same”,因为您只是创建了两个指向同一个对象的变量(即您将 c1 的引用传递给该对象c2):

    myclass c1 = new myclass();
    myclass c2 = c1;

    if (c1.GetHashCode() == c2.GetHashCode())
        Console.Write("Same");

当然,我认为这不是您想要实现的目标。

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 to c2):

    myclass c1 = new myclass();
    myclass c2 = c1;

    if (c1.GetHashCode() == c2.GetHashCode())
        Console.Write("Same");

Of course, I don't think this is what you're looking to achieve.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文