public class NameComparer : IEqualityComparer<FileInfo>
{
public bool Equals(FileInfo x, FileInfo y)
{
if (x == y)
{
return true;
}
if (x == null || y == null)
{
return false;
}
return string.Equals(x.FullName, y.FullName, StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode (FileInfo obj)
{
return StringComparer.OrdinalIgnoreCase.GetHashCode(obj.FullName);
}
}
You should first return true if the FileInfo's equality operator returns true. Also, specify the type of string comparison you want to do. Presumably you'd want to ignore case, since these are filenames.
public class NameComparer : IEqualityComparer<FileInfo>
{
public bool Equals(FileInfo x, FileInfo y)
{
if (x == y)
{
return true;
}
if (x == null || y == null)
{
return false;
}
return string.Equals(x.FullName, y.FullName, StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode (FileInfo obj)
{
return StringComparer.OrdinalIgnoreCase.GetHashCode(obj.FullName);
}
}
public sealed class FullNameComparer : IEqualityComparer<FileSystemInfo>
{
public bool Equals(FileSystemInfo x, FileSystemInfo y)
{
if (x == y)
{
return true;
}
if (x == null || y == null)
{
return false;
}
return String.Equals(x.FullName.TrimEnd('\\'), y.FullName.TrimEnd('\\'), StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode(FileSystemInfo obj)
{
return obj.FullName.GetHashCode();
}
}
Comparing just the Name will only work if you're always comparing files of the same directory. I suggest comparing by FullName instead.
You can easily extend the scope of the equality comparer to directories by implementing it for FileSystemInfo, the base class of FileInfo and DirectoryInfo.
public sealed class FullNameComparer : IEqualityComparer<FileSystemInfo>
{
public bool Equals(FileSystemInfo x, FileSystemInfo y)
{
if (x == y)
{
return true;
}
if (x == null || y == null)
{
return false;
}
return String.Equals(x.FullName.TrimEnd('\\'), y.FullName.TrimEnd('\\'), StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode(FileSystemInfo obj)
{
return obj.FullName.GetHashCode();
}
}
发布评论
评论(2)
如果 FileInfo 的相等运算符返回 true,则您应该首先返回 true。另外,指定要进行的字符串比较的类型。想必您想忽略大小写,因为这些是文件名。
You should first return true if the FileInfo's equality operator returns true. Also, specify the type of string comparison you want to do. Presumably you'd want to ignore case, since these are filenames.
仅当您始终比较同一目录的文件时,仅比较
名称
才有效。我建议改为通过FullName
进行比较。通过为
FileSystemInfo
(FileInfo
和DirectoryInfo
的基类)实现它,您可以轻松地将相等比较器的范围扩展到目录。Comparing just the
Name
will only work if you're always comparing files of the same directory. I suggest comparing byFullName
instead.You can easily extend the scope of the equality comparer to directories by implementing it for
FileSystemInfo
, the base class ofFileInfo
andDirectoryInfo
.