字典到自定义KeyValuePair列表 - 无法转换(C#.Net 4.0)

时间:2013-03-10 19:13:04

标签: c# .net dictionary

我读到了字典,并且xml序列化程序无法写入KeyValuePair。 所以我编写了自己的KeyValuePair结构。

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,但不适用于我自定义的keyValuePair。所以有什么问题? 我试图尽可能地复制原始文件,但它不想将我的字典(模板)转换为该列表。我看不到它使用任何接口或从结构继承来做到这一点。我是否必须手动添加所有条目?

1 个答案:

答案 0 :(得分: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();
相关问题