c# - 自动字典键?

标签 c# dictionary hashtable

我一直在谷歌上搜索了一段时间,我发现让您拥有一个包含具有相应唯一键的变量的列表的最佳方法是 HashTableDictionary,但我没有找到任何可以让你拥有自动键(整数类型)的东西。我想调用一个函数,将一个对象(作为参数传递)添加到字典并返回自动生成的键(int),并且没有任何键重复。我怎么能做到这一点?我完全在挣扎!

编辑:澄清事情。这是一个服务器,我想为每个客户端分配一个唯一的 key 。如果我使用最大键值,这个值很快就会在大型服务器上达到 int 最大值。因为如果客户端连接然后断开连接,他会留下一个未使用的值,应该重新使用该值以避免达到非常高的 key 最大值。

最佳答案

应该执行以下操作,它会重新使用释放的 key :

internal class AutoKeyDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable
{
    private readonly Dictionary<TKey, TValue> inner;
    private readonly Func<TKey, TKey> incrementor;
    private readonly Stack<TKey> freeKeys;
    private readonly TKey keySeed;
    private TKey currentKey;

    public AutoKeyDictionary(TKey keySeed, Func<TKey, TKey> incrementor) 
    {
        if (keySeed == null)
            throw new ArgumentNullException("keySeed");

        if (incrementor == null)
            throw new ArgumentNullException("incrementor");

        inner = new Dictionary<TKey, TValue>();
        freeKeys = new Stack<TKey>();
        currentKey = keySeed;
    }

    public TKey Add(TValue value) //returns the used key
    {
        TKey usedKey;

        if (freeKeys.Count > 0)
        {
            usedKey = freeKeys.Pop();
            inner.Add(usedKey, value);
        }
        else
        {
            usedKey = currentKey;
            inner.Add(usedKey, value);
            currentKey = incrementor(currentKey);
        }

        return usedKey;
    }

    public void Clear()
    {
        inner.Clear();
        freeKeys.Clear();
        currentKey = keySeed;
    }

    public bool Remove(TKey key)
    {
        if (inner.Remove(key))
        {
            if (inner.Count > 0)
            {
                freeKeys.Push(key);
            }
            else
            {
                freeKeys.Clear();
                currentKey = keySeed;
            }

            return true;
        }

        return false;
    }

    public bool TryGetValue(TKey key, out TValue value) { return inner.TryGetValue(key, out value); }
    public TValue this[TKey key] { get {return inner[key];} set{inner[key] = value;} }
    public bool ContainsKey(TKey key) { return inner.ContainsKey(key); }
    public bool ContainsValue(TValue value) { return inner.ContainsValue (value); }
    public int Count { get{ return inner.Count; } }
    public Dictionary<TKey,TValue>.KeyCollection Keys { get { return inner.Keys; } }
    public Dictionary<TKey, TValue>.ValueCollection Values { get { return inner.Values; } }
    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return inner.GetEnumerator(); }
    IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)inner).GetEnumerator(); }
}

免责声明:我没有测试过这段代码,它可能有一些不太重要的严重错误,一般方法是合理的。

关于c# - 自动字典键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39103022/

相关文章:

c# - UINavigationBar 在键盘打开时被推出屏幕(UITextView)

c# - 使用空数组反序列化 XML 返回一个包含单个对象的数组

python - 将字典的值更改为列表

python 3.6 : create new dict using values from another as indices

ruby-on-rails - Rails 中的哈希表

java - Java HashMap 调整大小的时间复杂度

c# - WCF REST 服务返回 JSONP 没有错误,但也没有数据

c# - 无法使 nunit 测试异常起作用。使用 .net 2.0

c# - 保存用户消息的静态字典

c# - 如何让一个方法接受两种类型的数据作为参数?