是否有类型安全的有序字典替代方案? [重复]

问题描述

|                                                                                                                   这个问题已经在这里有了答案:                                                      

解决方法

如果值的顺序很重要,请不要使用字典。我脑海中浮现的东西是SortedDictionary或
List<KeyValuePair>
。     ,如果找不到替换项,并且不想更改正在使用的集合类型,则最简单的方法可能是在OrderedDictionary周围编写类型安全的包装。 它正在执行与您现在正在做的相同的工作,但是非类型安全的代码受到的限制更大,仅在这一类中。在此类中,我们只能依靠其中包含TKey和TValue类型的后备字典,因为只能从我们自己的Add方法中插入它。在应用程序的其余部分,您可以将其视为类型安全的集合。
public class OrderedDictionary<TKey,TValue> : IDictionary<TKey,TValue> {
    private OrderedDictionary backing = new OrderedDictionary();

    // for each IDictionary<TKey,TValue> method,simply call that method in 
    // OrderedDictionary,performing the casts manually. Also duplicate any of 
    // the index-based methods from OrderedDictionary that you need.

    void Add(TKey key,TValue value)
    {
        this.backing.Add(key,value);
    }

    bool TryGetValue(TKey key,out TValue value)
    {
        object objValue;
        bool result = this.backing.TryGetValue(key,out objValue);
        value = (TValue)objValue;
        return result;
    }

    TValue this[TKey key]
    {
        get
        {
            return (TValue)this.backing[key];
        }
        set
        {
            this.backing[key] = value;
        }
    }
}
    ,如果您可以根据密钥对其进行排序,那么SortedDictionary可能适合您。 AFAIK没有OrderedDictionary的通用实现,除非您实现了一个。     ,由于OrderedDictionary没有TryGetValue方法,因此我不得不根据他的出色建议重写David Yaw的TryGetValue。这是我的修改。
    bool TryGetValue(TKey key,out TValue value)
    {
        object objValue;
        value = default(TValue);
        try
        {
            objValue = this.backing[key];
            value = (TValue)objValue;
        }
        catch
        {
            return false;
        }
        return true;
    }