C# - 字典 - 文件路径(Custom EqualityComparer)

时间:2014-05-20 10:25:17

标签: c# .net dictionary comparison string-comparison

问题:自定义对象实现了EqualityComparer和IEquatable,但是Dictionary并不总是使用这些方法。

上下文:我创建了一个帮助程序类FilePath,用于处理文件路径而不是将它们视为字符串。辅助类负责确定两个文件路径是否相等。然后,我需要将FilePath存储在Dictionary<FilePath, object>

目标:

  Assert.True(new FilePath(@"c:\temp\file.txt").Equals(
      new FilePath(@"C:\TeMp\FIle.tXt")); 

  var dict = new Dictionary<FilePath, object>
  {
      {new FilePath(@"c:\temp\file.txt"), new object()}
  }

  Assert.True(dict.ContainsKey(new FilePath(@"c:\temp\file.txt"));

  Assert.True(dict.ContainsKey(new FilePath(@"C:\TeMp\FIle.tXt"));

我已经创建了我的FilePath类:    公共类FilePath:EqualityComparer,IEquatable     {         私有字符串_fullPath;

    public FilePath (string fullPath)
    {
        _fullPath = Path.GetFullPath(fullPath);
    }

    public override bool Equals(FilePath x, FilePath y)
    {
        if (null == x || null == y)
            return false;

        return (x._fullPath.Equals(y._fullPath, StringComparison.InvariantCultureIgnoreCase));
    }

    public override int GetHashCode(FilePath obj)
    {
        return obj._fullPath.GetHashCode();
    }

    public bool Equals(FilePath other)
    {
        return Equals(this, other);
    }

    public override bool Equals(object obj)
    {
        return Equals(this, obj as FilePathSimple);
    }
}

问题:

断言1和2通过,但断言3失败:

 Assert.True(dict.ContainsKey(new FilePath(@"C:\TeMp\FIle.tXt"));

1 个答案:

答案 0 :(得分:2)

我还需要覆盖GetHashCode():

 public override int GetHashCode()
 {
     return _fullPath.ToLower().GetHashCode();
 }

参考文献:What's the role of GetHashCode in the IEqualityComparer<T> in .NET?

Compiler Warning (level 3) CS0659