Paradox Game Engine  v1.0.0 beta06
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros Pages
DictionaryDataConverter.cs
Go to the documentation of this file.
1 // Copyright (c) 2014 Silicon Studio Corp. (http://siliconstudio.co.jp)
2 // This file is distributed under GPL v3. See LICENSE.md for details.
3 using System;
4 using System.Collections.Generic;
5 
6 namespace SiliconStudio.Core.Serialization.Converters
7 {
8  public class DictionaryDataConverter<TData, T, TDataKey, TDataValue, TKey, TValue> : DataConverter<TData, T> where TData : class, IDictionary<TDataKey, TDataValue> where T : class, IDictionary<TKey, TValue>
9  {
10  public override void ConvertToData(ConverterContext converterContext, ref TData data, T obj)
11  {
12  if (obj == null)
13  {
14  data = null;
15  return;
16  }
17 
18  if (data == null)
19  {
20  // Optimize most common cases
21  if (typeof(TData) == typeof(Dictionary<TDataKey, TDataValue>) || typeof(TData) == typeof(IDictionary<TDataKey, TDataValue>))
22  data = (TData)(IDictionary<TDataKey, TDataValue>)new Dictionary<TDataKey, TDataValue>(obj.Count);
23  else
24  data = Activator.CreateInstance<TData>();
25  }
26  else
27  {
28  data.Clear();
29  }
30 
31  foreach (var item in obj)
32  {
33  var itemData1 = default(TDataKey);
34  var itemData2 = default(TDataValue);
35  converterContext.ConvertToData(ref itemData1, item.Key);
36  converterContext.ConvertToData(ref itemData2, item.Value);
37  data.Add(itemData1, itemData2);
38  }
39  }
40 
41  public override void ConvertFromData(ConverterContext converterContext, TData data, ref T source)
42  {
43  if (data == null)
44  {
45  source = null;
46  return;
47  }
48 
49  if (source == null)
50  {
51  // Optimize most common cases
52  if (typeof(T) == typeof(Dictionary<TKey, TValue>) || typeof(T) == typeof(IDictionary<TKey, TValue>))
53  source = (T)(IDictionary<TKey, TValue>)new Dictionary<TKey, TValue>(data.Count);
54  else
55  source = Activator.CreateInstance<T>();
56  }
57  else
58  {
59  source.Clear();
60  }
61 
62  foreach (var item in data)
63  {
64  var itemData1 = default(TKey);
65  var itemData2 = default(TValue);
66  converterContext.ConvertFromData(item.Key, ref itemData1);
67  converterContext.ConvertFromData(item.Value, ref itemData2);
68  source.Add(itemData1, itemData2);
69  }
70  }
71  }
72 }
Base class for converters to/from a data type.
override void ConvertToData(ConverterContext converterContext, ref TData data, T obj)
Converts the given source object to its data counterpart.