【发布时间】:2010-07-23 23:45:11
【问题描述】:
我发现自己经常遇到这个问题:我有一个字典,其中键是一些简单的数字 ID,值是对象。 ID 也包含在该值对象的特定属性中。
然后,我希望能够反序列化一些(格式不灵活)XML,如下所示:
<listitem>
<id>20359</id>
<someotherval>foo</someotherval>
</listitem>
<listitem>
...
这需要我使用 List<V> 反序列化,并且必须手动将其转换为 Dictionary<K,V> 很不方便。
第二个问题是绑定。绑定列表要求源实现ICollection(如果我没记错的话),而且不得不手动创建一个新的List<V> 并从Dictionary<K,V> 填充它是很痛苦的。
我目前的,相当丑陋但实用的解决方案是拥有以下类:
public abstract class Keyed<KeyType>
{
public KeyType key { get; set; }
}
public class KeyedDictionary<KeyType, ValueType> :
Dictionary<KeyType, ValueType>
where ValueType : Keyed<KeyType>
{
// ...
}
public class KeyedList<KeyType, ValueType> :
IList<ValueType>,
System.Collections.IList
where ValueType : Keyed<KeyType>
{
public readonly KeyedDictionary<KeyType, ValueType> dict =
new KeyedDictionary<KeyType, ValueType>();
// ...
}
这可行,但它内部又大又丑。有没有更好的办法?
编辑:这是我确定的解决方案。
public interface IKeyed<KeyType>
{
KeyType Key { get; }
}
public class KeyedList<KeyType, ValueType> :
KeyedCollection<KeyType, ValueType>
where ValueType : IKeyed<KeyType>
{
protected override KeyType GetKeyForItem(ValueType item) { return item.Key; }
}
【问题讨论】:
-
这实际上对我来说似乎相当不错。它满足要求,并且是简单的泛型和接口,没有什么大不了的。
-
除非您的问题是关于 C# 编程语言,否则请不要在标题中添加“C#”。这个问题是关于 .NET,而不是关于 C#。 C# 只是您编写的语言,因此您可以使用 .NET。
标签: c# .net data-binding dictionary xml-serialization