Rob*_*tka 0 .net c# dictionary
我读到了字典和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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我这样做时,我收到一个错误,它无法转换:
List<CustomKeyValuePair<string, AnimationPath>> convList =
Templates.ToList<CustomKeyValuePair<string, AnimationPath>>();
Run Code Online (Sandbox Code Playgroud)
它适用于普通的keyValuePair,但不适用于我的自定义keyValuePair.所以有什么问题?我试图尽可能地复制原始文件,但它不想将我的字典(模板)转换为该列表.我看不到它使用任何接口或从结构继承来做到这一点.我是否必须手动添加所有条目?
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
Run Code Online (Sandbox Code Playgroud)
这就是为什么ToList()有KeyValuePair作品,而另一个没有.
你最好的选择可能是使用:
List<CustomKeyValuePair<string, AnimationPath>> convList =
Templates.Select(kv => new CustomKeyValuePair(kv.Key, kv.Value)).ToList();
Run Code Online (Sandbox Code Playgroud)