2010-11-16 85 views
0

我有一个自定义对象(DataPointCollection),它具有两个整型属性和一个Guid属性。我希望该对象生成一个HashCode,以便在这些属性中没有两个具有相同值的对象被添加到HashSet中。我知道我需要重写GetHashCode()方法,但我该如何生成哈希代码来完成此操作?生成对象的哈希代码

下面是我想要如何使用它。

Dim dataPointCollections As New HashSet(Of DataPointCollection)() 

For Each row As DataRow In myDataSet.Tables(0).Rows 

    Dim dataPointCollection As New DataPointCollection() 
    dataPointCollection.ProjectID = row("ProjectID") 'Integer' 
    dataPointCollection.RoleID = row("RoleID") 'Integer' 
    dataPointCollection.ResourceGUID = row("ResourceGUID") 'Guid' 

    If Not dataPointCollections.Contains(dataPointCollection) Then 
    dataPointCollections.Add(dataPointCollection) 
    End If 

Next 

我打开其他的想法,但我认为这可能是比做对的对象集合的LINQ查询更快的(有可能是一个非常大的数字,这些对象)。

回答

4

您需要覆盖GetHashCodeEquals - 这两个组合将被HashSet使用。

你的平等检查应:

  • 检查其他物体是同一类型的,因为这对象(这是简单的,如果DataPointCollection是密封型;平等和继承是凌乱结合时)
  • 比较三个字段相等

您的哈希码检查需要结合三个字段;结果不是必须是唯一的;对于性能来说,它是更好如果两个不相等的对象有不同的哈希码,但这不是必需的。绝对要求是两个相同的对象具有相同的哈希码。我会做这样的事情(C#,但很容易转换为VB):

public override int GetHashCode() 
{ 
    int hash = 17; 
    hash = hash * 31 + projectId; 
    hash = hash * 31 + roleId; 
    hash = hash * 31 + resourceGuid.GetHashCode(); 
    return hash; 
} 
1

如果我理解正确的话,你只需要重写你的DataPointCollectionGetHashCodeEquals方法,用该方法在this question生成散列码。