我发现自己经常面临这个问题:我有一个字典,其中的关键是一些简单的数字ID和值是一个对象。该ID也包含在该值对象的特定属性中。字典<K,V>实现IList <V>
然后,我希望能够反序列化一些(格式不灵活),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; }
}
这对我来说确实很不错。它符合要求,它是直接的泛型和接口,没有tomfoolery。 – 2010-07-24 00:00:36
除非你的问题是关于C#编程语言,否则请保留“C#”。这个问题是关于.NET,而不是关于C#。 C#就是您正在编写的语言,以便您可以使用.NET。 – 2010-07-24 01:37:33