简体   繁体   English

C#-字典-文件路径(自定义EqualityComparer)

[英]C# - Dictionary - File Path (Custom EqualityComparer)

Problem: Custom Object implements EqualityComparer and IEquatable, but Dictionary doesn't always use these methods. 问题:自定义对象实现EqualityComparer和IEquatable,但是Dictionary并不总是使用这些方法。

Context: I have created a helper class, FilePath for dealing with file paths instead of treating them as strings. 上下文:我创建了一个辅助类FilePath来处理文件路径,而不是将它们视为字符串。 The helper class is responsible for determining if two file paths are equal. helper类负责确定两个文件路径是否相等。 I then need to store FilePaths in a Dictionary<FilePath, object> . 然后,我需要将FilePaths存储在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; 我创建了FilePath类: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: 断言1和2通过,但断言3失败:

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

I needed to override GetHashCode() as well: 我还需要重写GetHashCode():

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

References: What's the role of GetHashCode in the IEqualityComparer<T> in .NET? 参考: .NET中IEqualityComparer <T>中GetHashCode的作用是什么?

Compiler Warning (level 3) CS0659 编译器警告(等级3)CS0659

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM