C# Serialization and Deserialization Guide
In C#, serialization and deserialization can be used to convert objects into byte streams or strings for transferring or storing data between different applications.
To achieve serialization and deserialization, you need to use the relevant classes and interfaces in the System.Runtime.Serialization namespace. Below is a simple example demonstrating how to implement serialization and deserialization in C#.
- Create a class that can be serialized, which must be marked with the attribute [Serializable] to indicate that it can be serialized.
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
- Use the BinaryFormatter class from the System.Runtime.Serialization.Formatters.Binary namespace for serialization and deserialization.
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class Program
{
public static void Main(string[] args)
{
// 创建一个 Person 对象
Person person = new Person
{
Name = "John",
Age = 30
};
// 序列化对象
byte[] serializedData = SerializeObject(person);
// 反序列化对象
Person deserializedPerson = DeserializeObject<Person>(serializedData);
// 输出反序列化后的对象的属性值
Console.WriteLine($"Name: {deserializedPerson.Name}");
Console.WriteLine($"Age: {deserializedPerson.Age}");
}
// 序列化对象
public static byte[] SerializeObject<T>(T obj)
{
BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream memoryStream = new MemoryStream())
{
formatter.Serialize(memoryStream, obj);
return memoryStream.ToArray();
}
}
// 反序列化对象
public static T DeserializeObject<T>(byte[] data)
{
BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream memoryStream = new MemoryStream(data))
{
return (T)formatter.Deserialize(memoryStream);
}
}
}
In the given example, a serializable Person class is first defined. Next, a Person object is created in the Main method and serialized into a byte array. Then, the byte array is deserialized back into a Person object using the DeserializeObject method, and its property values are outputted.
Please note that the above example uses the BinaryFormatter class for serialization and deserialization. Other serialization methods, such as XML serialization (XmlSerializer) or JSON serialization (Json.NET), can also be used to achieve serialization and deserialization.