字典到自定义KeyValuePair列表-不能转换(c# . net 4.0)

本文关键字:net 转换 不能 自定义 KeyValuePair 列表 字典 | 更新日期: 2023-09-27 18:03:17

我读到字典和KeyValuePair不能由xml序列化器编写。所以我写了我自己的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列表-不能转换(c# . net 4.0)

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();