在C#中,實體類序列化可以通過使用Serializable特性來實現。Serializable特性告訴編譯器該類可以被序列化,即可以將對象轉換為字節流或其他格式以便保存或傳輸。
以下是一個示例實體類的序列化操作方法:
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class SerializationExample
{
public void SerializeObject(string filePath, object obj)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
}
public object DeserializeObject(string filePath)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
object obj = formatter.Deserialize(stream);
stream.Close();
return obj;
}
public static void Main()
{
Person person = new Person
{
Name = "John",
Age = 30
};
SerializationExample example = new SerializationExample();
example.SerializeObject("person.dat", person);
Person deserializedPerson = (Person)example.DeserializeObject("person.dat");
Console.WriteLine($"Deserialized person - Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}");
}
}
在上面的示例中,我們定義了一個名為Person的可序列化實體類,并創建了一個SerializationExample類來執行序列化和反序列化操作。在Main方法中,我們實例化了一個Person對象,并調用SerializeObject方法將其序列化到名為person.dat的文件中。然后,我們從該文件中反序列化對象,并打印出反序列化后的Person對象的屬性值。