public class SampleClass : SampleClassBase { public DateTime TimeStamp; } public class SampleClass2 : SampleClass { }
public static class SampleClassBaseExtensions { public static T LoadFromFile<T>(this T @this, string fileName) where T : SampleClassBase => SampleClassBase.LoadFromFile<T>(fileName); } public abstract class SampleClassBase { public int Number; public string Message;
public void SaveToFile(string fileName) { using (var sw = new System.IO.StreamWriter(fileName, false, new System.Text.UTF8Encoding(false))) { var serializer = new System.Xml.Serialization.XmlSerializer(GetType()); serializer.Serialize(sw, this); sw.Close(); } }
public static T LoadFromFile<T>(string fileName) where T : SampleClassBase { using (var sr = new System.IO.StreamReader(fileName, new System.Text.UTF8Encoding(false))) { var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); var obj = (T)serializer.Deserialize(sr); sr.Close(); return obj; } } }
class MainClass { public static void Main() { string fileName = @"C:\test\sample.xml";
SampleClass obj0 = new SampleClass { Message = "テストです。", Number = 123, TimeStamp = DateTime.Now };
// <SampleClass>〜</SampleClass> な XML として保存される obj0.SaveToFile(fileName);
// <SampleClass> な XML を SampleClass 以外の型に復元することはできない // var obj1 = SampleClassBase.LoadFromFile<SampleClassBase>(fileName); // var obj2 = SampleClassBase.LoadFromFile<SampleClass2>(fileName);