我發現自己經常面臨這個問題:我有一個字典,其中的關鍵是一些簡單的數字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