如何确保我的类的2个实例具有相同的哈希码?

时间:2018-08-24 08:16:52

标签: c# equals hashset

如何确保一个类的两个不同实例具有相同的哈希码?因此,当其中一个位于HashSet中时,Contains函数将返回true

这是我的代码:

public class Position
 {
     public int row, col;
     public override bool Equals(object obj)
     {
         return ((Position)obj).row == row && ((Position)obj).col == col;
     }
 }

这是我的用法:

HashSet<Position> hash = new HashSet<Position>();
Position position = new Position(3, 1);
Position position2 = new Position(3, 1);
hash.Add(position);
Console.WriteLine(hash.Contains(position2));

1 个答案:

答案 0 :(得分:-2)

using System;
using System.Text;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");
        HashSet<Position> hash = new HashSet<Position>();
        Position position = new Position(3, 1);
        Position position2 = new Position(3, 1);
        hash.Add(position);
        Console.WriteLine(hash.Contains(position2));
    }
}


public class Position
 {
     public int row, col;

     public Position(int row, int col) {
       this.row =  row;
        this.col =  col;
     }

     public override bool Equals(object obj)
     {
         return ((Position)obj).row == row && ((Position)obj).col == col;
     }

     public override int GetHashCode()
     {
        Console.WriteLine((row + col) * (row - col + 1));
        return (row + col) * (row - col + 1);
     }
 }