我想在字典中保存一些对.
最后,我想将字典序列化为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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果值的顺序很重要,请不要使用字典。我脑海中浮现出的东西是 SortedDictionary 或List<KeyValuePair>
.
归档时间: |
|
查看次数: |
5133 次 |
最近记录: |