3

この回答hereの HashCode 構造体に基づいて GetHashCode() の実装に取り​​組んでいます。Equals メソッドは Enumerable.SequenceEqual() を使用してコレクションを考慮するため、GetHashCode() 実装にコレクションを含める必要があります。

出発点として、Jon Skeet の組み込み GetHashCode() 実装を使用して、HashCode 構造体実装の出力をテストしています。これは、以下の次のテストを使用して期待どおりに機能します-

private class MyObjectEmbeddedGetHashCode
{
    public int x;
    public string y;
    public DateTimeOffset z;

    public List<string> collection;

    public override int GetHashCode()
    {
        unchecked
        {
            int hash = 17;

            hash = hash * 31 + x.GetHashCode();
            hash = hash * 31 + y.GetHashCode();
            hash = hash * 31 + z.GetHashCode();

            return hash;
        }
    }
}

private class MyObjectUsingHashCodeStruct
{
    public int x;
    public string y;
    public DateTimeOffset z;

    public List<string> collection;

    public override int GetHashCode()
    {
        return HashCode.Start
            .Hash(x)
            .Hash(y)
            .Hash(z);
    }
}

[Test]
public void GetHashCode_CollectionExcluded()
{
    DateTimeOffset now = DateTimeOffset.Now;

    MyObjectEmbeddedGetHashCode a = new MyObjectEmbeddedGetHashCode() 
    { 
        x = 1, 
        y = "Fizz",
        z = now,
        collection = new List<string>() 
        { 
            "Foo", 
            "Bar", 
            "Baz" 
        } 
    };

    MyObjectUsingHashCodeStruct b = new MyObjectUsingHashCodeStruct()
    {
        x = 1,
        y = "Fizz",
        z = now,
        collection = new List<string>() 
        { 
            "Foo", 
            "Bar", 
            "Baz" 
        }
    };

    Console.WriteLine("MyObject::GetHashCode(): {0}", a.GetHashCode());
    Console.WriteLine("MyObjectEx::GetHashCode(): {0}", b.GetHashCode());

    Assert.AreEqual(a.GetHashCode(), b.GetHashCode());
}

次のステップは、GetHashCode() 計算でコレクションを考慮することです。これには、MyObjectEmbeddedGetHashCode の GetHashCode() 実装に少し追加する必要があります。

public override int GetHashCode()
{
    unchecked
    {
        int hash = 17;

        hash = hash * 31 + x.GetHashCode();
        hash = hash * 31 + y.GetHashCode();
        hash = hash * 31 + z.GetHashCode();

        int collectionHash = 17;

        foreach (var item in collection)
        {
            collectionHash = collectionHash * 31 + item.GetHashCode();
        }

        hash = hash * 31 + collectionHash;

        return hash;
    }
}

ただし、これは HashCode 構造体では少し難しくなります。この例では、List 型のコレクションが Hash メソッドに渡されると、T は List なので、obj を ICollection または IEnumberable にキャストしようとしても機能しません。IEnumerable に正常にキャストできますが、ボクシングが発生し、IEnumerable を実装する文字列などの型を除外することについて心配する必要があることがわかりました。

このシナリオで obj を ICollection または IEnumerable に確実にキャストする方法はありますか?

public struct HashCode
{
    private readonly int hashCode;

    public HashCode(int hashCode)
    {
        this.hashCode = hashCode;
    }

    public static HashCode Start
    {
        get { return new HashCode(17); }
    }

    public static implicit operator int(HashCode hashCode)
    {
        return hashCode.GetHashCode();
    }

    public HashCode Hash<T>(T obj)
    {
        // I am able to detect if obj implements one of the lower level
        // collection interfaces. However, I am not able to cast obj to
        // one of them since T in this case is defined as List<string>,
        // so using as to cast obj to ICollection<T> or IEnumberable<T>
        // doesn't work.
        var isGenericICollection = obj.GetType().GetInterfaces().Any(
            x => x.IsGenericType && 
            x.GetGenericTypeDefinition() == typeof(ICollection<>));

        var c = EqualityComparer<T>.Default;

        // This works but using IEnumerable causes boxing.
        // var h = c.Equals(obj, default(T)) ? 0 : ( !(obj is string) && (obj is IEnumerable) ? GetCollectionHashCode(obj as IEnumerable) : obj.GetHashCode());

        var h = c.Equals(obj, default(T)) ? 0 : obj.GetHashCode();
        unchecked { h += this.hashCode * 31; }
        return new HashCode(h);
    }

    public override int GetHashCode()
    {
        return this.hashCode;
    }
}
4

1 に答える 1

4

コレクションの問題には、いくつかの方法で対処できます。

  1. ICollectionまたは などの非汎用インターフェイスを使用しますIEnumerable
  2. Hash()メソッドのオーバーロードを追加します。Hash<T>(IEnumerable<T> list) { ... }

そうは言っても、私見はそのままにしてstruct HashCode、コレクション固有のコードを実際のGetHashCode()メソッドに入れる方が良いでしょう。例えば:

public override int GetHashCode()
{
    HashCode hash = HashCode.Start
        .Hash(x)
        .Hash(y)
        .Hash(z);

    foreach (var item in collection)
    {
        hash = hash.Hash(item);
    }

    return hash;
}

タイプのフル機能バージョンが必要な場合は、struct HashCode参照した同じページにあるように見えます: https://stackoverflow.com/a/2575444/3538012

メンバーの命名は異なりますが、基本的に型と同じ考え方struct HashCodeですが、他の複雑な型のオーバーロードがあります (上記の私の提案 #2 のように)。それを使用するか、そこにあるテクニックを の実装に適用して、そこでstruct HashCode使用されている命名規則を維持することができます。

于 2015-02-16T19:26:25.353 に答える