Problem: Custom Object实现EqualityComparer和IEquatable,但Dictionary并不总是使用这些方法 .
Context: 我创建了一个辅助类 FilePath
来处理文件路径而不是将它们视为字符串 . 辅助类负责确定两个文件路径是否相等 . 然后我需要将FilePath存储在 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"));
我创建了我的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:
断言1和2通过,但断言3失败:
Assert.True(dict.ContainsKey(new FilePath(@"C:\TeMp\FIle.tXt"));
1 回答
我还需要覆盖GetHashCode():
参考文献:What's the role of GetHashCode in the IEqualityComparer<T> in .NET?
Compiler Warning (level 3) CS0659