2013-03-10 29 views
1

我讀過該字典並且KeyValuePair不能被xml序列化程序寫入。 所以我寫了我自己的KeyValuePair結構。Dictionary to Custom KeyValuePair list - 無法轉換(C#.Net 4.0)

public struct CustomKeyValuePair<Tkey, tValue> 
{ 
    public Tkey Key { get; set; } 
    public tValue Value { get; set; } 

    public CustomKeyValuePair(Tkey key,tValue value) : this() 
    { 
     this.Key = key; 
     this.Value = value; 
    } 
} 

但是當我這樣做,我得到一個錯誤,它不能轉換:

List<CustomKeyValuePair<string, AnimationPath>> convList = 
        Templates.ToList<CustomKeyValuePair<string, AnimationPath>>(); 

它工作在正常keyValuePair,卻沒有關於我的自定義一個。所以有什麼問題? 我試圖儘可能地將原件複製,但它不想將我的字典(模板)轉換爲該列表。我看不到它使用任何接口或從結構繼承來做到這一點。我是否必須手動添加所有條目?

+0

什麼是你的錯誤? – bas 2013-03-10 19:15:47

+3

模板的定義是什麼? – 2013-03-10 19:16:37

回答

6

Dictionary<Tkey, TValue>同時實現了IEnumerable<KeyValuePair<Tkey, Tvalue>>ICollection<KeyValuePair<Tkey, Tvalue>>

(在Visual Studio中顯示的元數據):

public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, 
    ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, 
    IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback 

這就是爲什麼ToList()KeyValuePair作品和其他沒有。

您最好的選擇可能是使用:

List<CustomKeyValuePair<string, AnimationPath>> convList = 
    Templates.Select(kv => new CustomKeyValuePair(kv.Key, kv.Value)).ToList(); 
+0

謝謝,那個作品:) 不知道字典從它繼承。 – 2013-03-10 20:38:48