<分区>
我想在字典中保存一些对。
最后我想将字典序列化为一个 JSON 对象。 然后我打印 JSON 内容。我希望这些对按照它们在字典中输入的顺序打印。
起初我用的是一本普通的字典。但后来我认为订单可能无法保留。然后我迁移到 OrderedDictionary,但它不使用 Generic,这意味着它不是类型安全的。
您还有其他好的解决方案吗?
标签 c# dictionary
<分区>
我想在字典中保存一些对。
最后我想将字典序列化为一个 JSON 对象。 然后我打印 JSON 内容。我希望这些对按照它们在字典中输入的顺序打印。
起初我用的是一本普通的字典。但后来我认为订单可能无法保留。然后我迁移到 OrderedDictionary,但它不使用 Generic,这意味着它不是类型安全的。
您还有其他好的解决方案吗?
最佳答案
如果找不到替代品,并且不想更改正在使用的集合类型,最简单的方法可能是围绕 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;
}
}
}
关于c# - 是否有类型安全的有序字典替代方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5411306/