Dictionary Serialization

CSharp · Console

/Program.cs

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections.Generic;
using System.Runtime.Serialization;

public class Program
{
	public static void Main()
	{

		// выполняем сериализацию коллекции
		var data = new MyDictionary();
		data.Add("Key", "Value");
		data.Add("Key2", "Value2");
		data.Add("Key3", 123);
		
		var bf = new BinaryFormatter();
		var m = new MemoryStream();
		bf.Serialize(m, data);
		Console.WriteLine("Serialize - OK");
		
		// выполняем десериализацию
		m.Position = 0;
		var result = (MyDictionary)bf.Deserialize(m);
		Console.WriteLine("Deserialize - OK");
		
		// выводим результат
		foreach (var item in result)
		{
		  Console.WriteLine("{0} = {1}", item.Key, item.Value);
		}
	}
	
	[Serializable]
	public class MyDictionary : Dictionary<string, object>, ISerializable
	{
	
	  public MyDictionary() { }
	
	  protected MyDictionary(SerializationInfo info, StreamingContext context)
	  {
		if (info == null)
		{
		  throw new ArgumentNullException("info");
		}
		int count = info.GetInt32("Count"); // получаем число элементов
		for (int i = 0; i < count; i++) // перебираем элементы
		{
		  // получаем ключ и значение по индексу элемента
		  string key = info.GetString(String.Format("ItemKey{0}", i));
		  object value = info.GetValue(String.Format("ItemValue{0}", i), typeof(object));
		  // добавляем элемент в себя
		  this.Add(key, value);
		}
	  }
	
	  public override void GetObjectData(SerializationInfo info, StreamingContext context)
	  {
		if (info == null)
		{
		  throw new ArgumentNullException("info");
		}
		// перебираем все элементы коллекции
		int i = 0;
		foreach (KeyValuePair<string, object> item in this)
		{
		  // добавляем отдельно ключ и значение
		  info.AddValue(String.Format("ItemKey{0}", i), item.Key, typeof(string));
		  info.AddValue(String.Format("ItemValue{0}", i), item.Value);
		  i++;
		}
		// запоминаем, сколько всего элементов
		info.AddValue("Count", this.Count);
	  }
	}
	
	
}
;