この回答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;
}
}