我读过 这个问题关于为什么这是不可能的,但是还没有找到解决这个问题的方法。
我希望从。NET HashSet<T>
.我正在寻找一种方法,它会有这样的签名:
/// <summary>
/// Determines if this set contains an item equal to <paramref name="item"/>,
/// according to the comparison mechanism that was used when the set was created.
/// The set is not changed. If the set does contain an item equal to
/// <paramref name="item"/>, then the item from the set is returned.
/// </summary>
bool TryGetItem<T>(T item, out T foundItem);
使用这种方法在集合中搜索项将是 O (1)。从 HashSet<T>
检索项的唯一方法是枚举所有 O (n)的项。
我还没有找到任何解决这个问题的方法,除了制作我自己的 HashSet<T>
或使用 Dictionary<K, V>
。还有别的办法吗?
注:
我不想检查 HashSet<T>
是否包含该项目。我希望获得对存储在 HashSet<T>
中的项的引用,因为我需要更新它(而不需要用另一个实例替换它)。我传递给 TryGetItem
的条目是相等的(根据我传递给构造函数的比较机制) ,但它不是相同的引用。