3

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

2 に答える 2

9

FileInfo の等価演算子が true を返す場合は、最初に true を返す必要があります。また、実行する文字列比較のタイプを指定します。これらはファイル名であるため、おそらく大文字と小文字を区別したくないでしょう。

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);
   }
}
于 2009-11-22T16:49:04.060 に答える
2

常に同じディレクトリのファイルを比較Nameしている場合にのみ機能します。代わりに比較することをお勧めしFullNameます。

およびFileSystemInfoの基本クラスであるに対して実装することにより、等値比較子のスコープをディレクトリに簡単に拡張できます。FileInfoDirectoryInfo

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();
    }
}
于 2013-05-15T16:18:30.193 に答える