문제

I don't see any problems with this code, but it feels like I'm missing something. Maybe it is possible to reduce the number of lines. Or is there even a bug to be fixed? I'm open to any suggestions.

public class NameComparer : IEqualityComparer<FileInfo>
{
    public bool Equals (FileInfo x, FileInfo y)
    {
        if (x == null) {
            return y == null;
        }

        if (y == null) {
            return false;   
        }

        return x.Name.Equals (y.Name);
    }

    public int GetHashCode (FileInfo obj)
    {
        return obj.Name.GetHashCode ();
    }
}
도움이 되었습니까?

해결책

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

다른 팁

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();
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top