是否可以让类在它使用的Dictionary<>
类中使用IEqualityComparer
指定的作为键,而不是在每次构造它时将其指定为参数?
public class mytest : IEqualityComparer<mytest>
{
public string name = "foo";
bool IEqualityComparer<mytest>.Equals(mytest x, mytest y) { return x.name == y.name; }
int IEqualityComparer<mytest>.GetHashCode(mytest obj) { return obj.name.GetHashCode(); }
public override int GetHashCode() { return name.GetHashCode(); }
}
...
var a = new Dictionary<mytest, int>();
a.Add(new mytest(), 1);
a.Add(new mytest(), 2);//does not throw error...bad!
var b = new Dictionary<mytest, int>(new mytest());
b.Add(new mytest(), 1);
b.Add(new mytest(), 2);//will throw error...good!