【问题标题】:Creating a unique hash code based on some properties of an object [duplicate]基于对象的某些属性创建唯一的哈希码[重复]
【发布时间】:2016-04-08 23:52:37
【问题描述】:

我必须参加以下课程:

public class NominalValue
{
   public int Id {get; set;}
   public string ElementName {get; set;}
   public decimal From {get; set;}  
   public decimal To {get; set;}    
   public bool Enable {get; set;}   
   public DateTime CreationDate {get; set;}
   public int StandardValueId {get; set;}  //FK for StandardValue
} 
public class StandardValue
{
   public int Id {get; set;}
   public string ElementName {get; set;}
   public decimal From {get; set;}  
   public decimal To {get; set;}    
   public bool Enable {get; set;}   
   public DateTime CreationDate {get; set;}
} 

用户想要填写nominalValue 对象属性。填充nominalValue 属性可以通过两种方式执行:

  1. 用户手动填写nominalValue 的值。
  2. 用户从standardValue 对象加载nominalValue 的值,然后更改或不更改某些值。

有时我需要知道指定元素的nominalValue 对象的某些属性是否等于对应的standardValue

我不想从Db 加载standardValue 来检查这个相等性,所以我决定在NominalValue 类中定义一个HashValue 属性:

public class NominalValue
{
   public int Id {get; set;}
   public string ElementName {get; set;}
   public decimal From {get; set;}  //<-- 1st parameter for generating hash value
   public decimal To {get; set;}    //<-- 2nd parameter for generating hash value
   public bool Enable {get; set;}   //<-- 3rd parameter for generating hash value 
   public DateTime CreationDate {get; set;}
   public int StandardValueId {get; set;}  
   public string HashValue {get;set;}      //<-- this property added
} 

当用户使用standardValue 属性填充nominalValue 属性时,我根据3 个属性(FromToEnable)计算其值并将其与其他属性一起保存,当我检查是否nominalValue 是否填充standardValue,我计算FromToEnable 的哈希码并将结果与​​HashValue 进行比较(而不是从Db 加载standardValue)。

是否有任何机制可以根据 3 个属性值(FromToEnable)计算唯一的哈希码?

【问题讨论】:

标签: c# hash compare


【解决方案1】:

你可以尝试做这样的事情:

private int GetHashValue() {
    unchecked 
    {
        int hash = 17;
        //dont forget nullity checks 
        hash = hash * 23 + From.GetHashCode();
        hash = hash * 23 + To.GetHashCode();
        hash = hash * 23 + Enable.GetHashCode();
        return hash;
    }
}

您也可以在匿名类型上使用 GetHashCode 方法

private int GetHashValue() {
   return new { From, To, Enable }.GetHashCode();
}

【讨论】:

  • 魔术数字应该总是被注释掉,尤其是在一个 SO 答案中。
  • 思路是取两个不同的素数,来自这本书amazon.com/dp/0321356683
  • 来自匿名对象的 GetHashCode 更加优雅和便携,在我看来应该是(单独)接受的答案。
猜你喜欢
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 2012-01-19
  • 1970-01-01
  • 1970-01-01
  • 2015-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多