开发者

Gethashcode() function

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

    }
}


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).


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜