如何实现此自定义平等?

时间:2011-07-15 14:39:23

标签: c# .net

我有一个符号实体,当与另一个实体相比时有这种行为:

  1. 如果FileName& FileDate为Equal,返回True
  2. 如果FileDate不同,则比较每个的CRC32并返回该值
  3. 我想知道如何在这种情况下实现此Equality,特别是GetHashCode()。

2 个答案:

答案 0 :(得分:1)

我会说(基于我对你的例子的理解),这样的事情。你可以包含一个更复杂的哈希代码,它与你的FileDate和CRC32相似,但实际上,因为常见的粘合剂始终是FileName,你可以将它用作代理哈希码。

请记住,Equal()对象永远不应该有不同的哈希码,但是!Equal()对象可能具有相同的哈希码(它只是潜在的冲突)。

此外,您还要注意作为哈希代码一部分的字段是可变的,否则对象的哈希码可以“更改”,这在字典中可能非常糟糕......

    public sealed class Symbol : IEquatable<Symbol>
    {
        public string FileName { get; set; }
        public DateTime FileDate { get; set; }
        public long CRC32 { get; set; }

        public bool Equals(Symbol other)
        {
            if (other == null)
            {
                return false;
            }

            return FileName == other.FileName &&
                   (FileDate == other.FileDate || CRC32 == other.CRC32);
        }

        public override bool Equals(object obj)
        {
            return Equals(obj as Symbol);
        }

        public override int GetHashCode()
        {
            // since FileName must be equal (others may or may not)
            // can use its hash code as your surrogate hash code.
            return FileName.GetHashCode();
        }
    }

答案 1 :(得分:0)

     public override bool Equals(object obj)     
    {         
    var file = obj as Symbol;
    if ( file.FileName == FileName && file.FileDate == FileDate )
        return true
    else    
return Boolean Value of [Compare CRC Here];      
      } 

以下是如何计算文件的CRC。

http://damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net

这基本上就是詹姆斯迈克尔黑尔所说的我只是慢了。

相关问题