【发布时间】:2015-01-20 14:12:49
【问题描述】:
我有一个包含以下内容的类:
HashSet<CookieSetItem> _set = new HashSet<CookieSetItem>();
public IEnumerable<CookieSetItem> Set
{
get { return _set; }
}
public void Add(int id)
{
id.ThrowDefault("id");
var item = new CookieSetItem(id);
if (_set.Add(item))
{
// this only happens for the first call
base.Add();
}
}
当我多次调用 add 方法时,比如 ID 为 1、2、3 等,只添加第一项。
显然我很困惑,因为每次都使用唯一元素(ID)创建一个新的 CookieSetItem,那么为什么不添加它呢?。
为了完整起见,这里是 cookie 集类:
public sealed class CookieSetItem
{
readonly DateTime _added;
readonly int _id;
public DateTime Added
{
get { return _added; }
}
public int ID
{
get { return _id; }
}
public CookieSetItem(int id)
: this(id, DateTime.Now)
{
}
public CookieSetItem(int id, DateTime added)
{
id.ThrowDefault("id");
added.ThrowDefault("added");
_id = id;
_added = added;
}
}
【问题讨论】:
-
您需要在
CookieSetItem中覆盖GetHashCode并返回对象的哈希码(如ID属性)或实现IEqualityComparer<CookieSetItem>并将其传递给HashSet构造函数。 -
_set.Add(item)是返回false还是base.Add()实际上并未“添加”该项目(最好知道base是什么以及base.Add做什么)。跨度> -
@DStanley - base.Add() 由于 hashset.Add 返回 false 而没有被调用
-
@SimonBelanger 如何允许添加实例 2、3 等?似乎如果
Equals没有被覆盖,那么可以毫无问题地添加其他实例。 -
请展示一个简短但完整的程序来说明问题。这里的信息太少,无法为您提供帮助。