我知道
那么简单的例子是什么?
特别地,如果我要比较的每个集合中还包含 HashSet,那么应该如何正确使用
这是我的起点。我想知道
忽略关于系统设计等方面的争议,一个简化的用例是:想象一下我已经获取了一个看起来像这样的复杂数据集:
HashSet<T>.SetEquals
方法,但是何时以及如何使用 CreateSetComparer
?
文档 指出:"仅在一个级别上检查相等性;但是,您可以链接比较器到其他级别以执行更深层次的相等性测试"。那么简单的例子是什么?
特别地,如果我要比较的每个集合中还包含 HashSet,那么应该如何正确使用
CreateSetComparer
?这是我的起点。我想知道
CreateSetComparer
方法是否适用以及如何正确使用它:public class Foo : IEquatable<Foo>
{
public string Label { get; set; }
public string Value { get; set; }
public override string ToString() {return String.Format("{0}:{1}", Label, Value); }
// assume for this example that Label and Value are immutable once set;
public override int GetHashCode(){ return ToString().GetHashCode(); }
// simplified equality check; assume it meets my needs for this example;
public bool Equals(Foo other){ return String.Equals(this.ToString(), other.ToString()); }
}
public class FooGroup : IEquatable<FooGroup>
{
public int GroupIndex {get; set;}
public HashSet<Foo> FooCollection {get; set;}
// -----------------------------
// Does HashSet.CreateSetComparer somehow eliminate or simplify the following code?
// -----------------------------
public override int GetHashCode()
{
int hash = GroupIndex;
foreach(Foo f in FooCollection)
hash = hash ^ (f.GetHashCode() & 0x7FFFFFFF);
return hash;
}
public bool Equals(FooGroup other)
{
// ignore missing null checks for this example
return this.GroupIndex == other.GroupIndex && this.FooCollection.SetEquals(other.FooCollection);
}
}
public class GroupCollection : IEquatable<GroupCollection>
{
public string CollectionLabel {get; set;}
public HashSet<FooGroup> AllGroups {get; set;}
// -----------------------------
// Does HashSet.CreateSetComparer somehow eliminate or simplify the following code?
// -----------------------------
public override int GetHashCode()
{
int hash = CollectionLabel.GetHashCode();
foreach(FooGroup g in AllGroups)
hash = hash ^ (g.GetHashCode() & 0x7FFFFFFF);
return hash;
}
public bool Equals(GroupCollection other)
{
// ignore missing null checks for this example
return String.Equals(this.CollectionLabel, other.CollectionLabel) && this.AllGroups.SetEquals(other.AllGroups);
}
}
忽略关于系统设计等方面的争议,一个简化的用例是:想象一下我已经获取了一个看起来像这样的复杂数据集:
var newSetA = new GroupCollection{ ... }
var oldSetA = new GroupCollection{ ... }
我只是想检查:
if (newSetA.Equals(oldSetA))
Process(newSetA);