C# - Dictionary - File Path (Custom EqualityComparer)

人走茶凉 提交于 2019-12-11 09:39:47

问题


Problem: Custom Object implements EqualityComparer and IEquatable, but Dictionary doesn't always use these methods.

Context: I have created a helper class, FilePath for dealing with file paths instead of treating them as strings. The helper class is responsible for determining if two file paths are equal. I then need to store FilePaths in a Dictionary<FilePath, object>.

Goal:

  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"));

I've created my FilePath class: public class FilePath : EqualityComparer, IEquatable { private string _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);
    }
}

Question:

Assert 1 and 2 pass, but Assert 3 fails:

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

回答1:


I needed to override GetHashCode() as well:

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

References: What's the role of GetHashCode in the IEqualityComparer<T> in .NET?

Compiler Warning (level 3) CS0659



来源:https://stackoverflow.com/questions/23757210/c-sharp-dictionary-file-path-custom-equalitycomparer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!