■
シリアライズ:バージョンによって内容が変わったらどうする?
#define v1 #define v2 #define w #define r using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace serialize { class Program { static void Main(string[] args) { SortedDictionary<ulong, status> d; var f = new BinaryFormatter(); #if (v1 && w) d = new SortedDictionary<ulong, status>(); d.Add(1, new status() { id = 1, text = "1" }); d.Add(2, new status() { id = 2, text = "2" }); d.Add(3, new status() { id = 3, text = "3" }); using (var s = new FileStream("test.dat", FileMode.Create)) { f.Serialize(s, d); } #elif (v2 && w) d = new SortedDictionary<ulong, status>(); d.Add(1, new status() { id = 11, text = "aa", created_at = new DateTime(1, 2, 3) }); d.Add(2, new status() { id = 12, text = "bb", created_at = new DateTime(2010, 1, 1, 12, 34, 56) }); d.Add(3, new status() { id = 13, text = "cc", created_at = DateTime.Now }); using (var s = new FileStream("test.dat", FileMode.Create)) { f.Serialize(s, d); } #elif r using (var s = new FileStream("test.dat", FileMode.Open)) { d = (SortedDictionary<ulong, status>)f.Deserialize(s); } foreach (var v in d) { Console.WriteLine(v); } #endif } } [Serializable] public class status { public ulong id; public string text; #if v1 public override string ToString() { return string.Format("id:{0} text:{1}", id, text); } #elif v2 [OptionalField(VersionAdded = 2)] public DateTime created_at; [OnDeserializing] // 初期値を入れる internal void OnDeserializingMethod(StreamingContext context) { created_at = DateTime.Now; } [OnDeserialized] // 読み込んだ他のデータを参照して値を入れるならこっち internal void OnDeserializedMethod(StreamingContext context) { if (id == 1) created_at = DateTime.Now.Subtract(new TimeSpan(1, 0, 0, 0)); } public override string ToString() { return string.Format("id:{0} text:{1} created_at:{2}", id, text, created_at); } #endif } }
こんな感じ
VersionAddedの値はどこで使うんだろう?