C# 物件的保存與復原:序列化與反序列化
序列化將資料儲存為可移植格式,方便物件在不同應用、系統或機器間傳輸。
要序列化對象,必須使用 [Serializable]
屬性標記,並包含無參數建構子。 此外,[XmlIgnore]
和 [JsonIgnore]
屬性可用於排除特定屬性或欄位。
範例
考慮以下 SomeClass
:
<code class="language-csharp">[Serializable] public class SomeClass { public string someProperty { get; set; } } SomeClass object1 = new SomeClass { someProperty = "someString" };</code>
儲存到檔案
二元序列化 (BinarySerialization):
<code class="language-csharp"> BinaryFormatter binaryFormatter = new BinaryFormatter(); using (Stream stream = File.Create("object1.bin")) { binaryFormatter.Serialize(stream, object1); }</code>
XML 序列化 (XMLSerialization):
<code class="language-csharp"> XmlSerializer serializer = new XmlSerializer(typeof(SomeClass)); using (TextWriter writer = new StreamWriter("object1.xml")) { serializer.Serialize(writer, object1); }</code>
JSON 序列化 (JsonSerialization):
<code class="language-csharp"> using (StreamWriter writer = new StreamWriter("object1.json")) { writer.Write(JsonConvert.SerializeObject(object1)); }</code>
從檔案還原
二元反序列化 (BinaryDeserialization):
<code class="language-csharp"> BinaryFormatter binaryFormatter = new BinaryFormatter(); using (Stream stream = File.OpenRead("object1.bin")) { object1 = (SomeClass)binaryFormatter.Deserialize(stream); }</code>
XML 反序列化 (XMLDeserialization):
<code class="language-csharp"> XmlSerializer serializer = new XmlSerializer(typeof(SomeClass)); using (TextReader reader = new StreamReader("object1.xml")) { object1 = (SomeClass)serializer.Deserialize(reader); }</code>
JSON 反序列化 (JsonDeserialization):
<code class="language-csharp"> using (StreamReader reader = new StreamReader("object1.json")) { object1 = JsonConvert.DeserializeObject<SomeClass>(reader.ReadToEnd()); }</code>
以上是如何在 C# 中序列化和反序列化物件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!