我有一个以前在 HashSet 中使用的类。现在已经对此进行了更改,以便该类现在在 SortedSet 中使用,但相等测试不再像以前那样工作。我相信它使用 CompareTo 函数进行排序和比较,这是设计使然。
除了执行我自己的重复检查之外,还有人有任何想法吗?
public sealed class DatedID : IEquatable<DatedID>, IComparable
{
readonly DateTime _added;
readonly int _ID;
public DateTime Added
{
get { return _added; }
}
public int ID
{
get { return _ID; }
}
public DatedID(int id)
: this(id, DateTime.Now) {}
public DatedID(int id, DateTime added)
{
id.ThrowDefault("id");
added.ThrowDefault("added");
_ID = id;
_added = added;
}
// Compare
int IComparable.CompareTo(object obj)
{
var other = (DatedID)obj;
// Newest => oldest
return this.Added > other.Added ? -1 : this.Added < other.Added ? 1 : 0;
}
// Equals
public bool Equals(DatedID other)
{
if (other == null) return false;
return this.ID == other.ID;
}
public override bool Equals(object obj)
{
if (obj == null) return false;
var di = obj as DatedID;
return di == null ? false : Equals(di);
}
public override int GetHashCode()
{
return ID.GetHashCode();
}
}
最佳答案
如果您的意思是需要能够处理具有不同 ID 但相同 DateTime
的多个值,您可以将其包含在您的 CompareTo
实现中:
// TODO: Implement IComparable<DatedID> as well :)
int IComparable.CompareTo(object obj)
{
var other = (DatedID)obj;
int dateComparison = other.Added.CompareTo(this.Added);
return dateComparison != 0
? dateComparison
: _ID.CompareTo(other._ID);
}
如果您的意思是您不希望能够添加具有相同 ID 但不同日期的多个值,那么您无法使用 SortedSet
实现这一点。在 SortedSet
中,唯一的相等性衡量标准是比较是否返回 0。
关于c# - SortedSet<T> 需要使用不同的排序和相等标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28071629/