Reputation:
I read that dictionary and KeyValuePair can not be written by the xml serializer. So I wrote my own KeyValuePair struct.
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;
}
}
But when I do this, I get an error, that it can't convert:
List<CustomKeyValuePair<string, AnimationPath>> convList =
Templates.ToList<CustomKeyValuePair<string, AnimationPath>>();
It works on the normal keyValuePair, but not on my custom one. So whats the problem? I tried to copy the original as close as possible, but it doesn't want to convert my dictionary (Templates) to that list. I can't see that it uses any interface or inherits from a struct to do that. Do I have to add all the entries manually?
Upvotes: 0
Views: 2115
Reputation: 101652
Dictionary<Tkey, TValue>
implements both IEnumerable<KeyValuePair<Tkey, Tvalue>>
and ICollection<KeyValuePair<Tkey, Tvalue>>
:
(from metadata shown in Visual Studio):
public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>,
ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>,
IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback
That's why ToList()
with KeyValuePair
works and the other doesn't.
Your best bet is probably to use:
List<CustomKeyValuePair<string, AnimationPath>> convList =
Templates.Select(kv => new CustomKeyValuePair(kv.Key, kv.Value)).ToList();
Upvotes: 5