在C#中,要对结构体(struct)进行序列化,可以使用System.Runtime.Serialization
命名空间中的BinaryFormatter
类。以下是一个简单的示例:
首先,创建一个结构体:
using System; namespace SerializationExample { [Serializable] public struct Person { public string Name; public int Age; public string Address; } }
注意,我们在结构体上添加了[Serializable]
属性,这是进行序列化的必要条件。
接下来,创建一个序列化方法和一个反序列化方法:
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace SerializationExample
{
public class SerializationHelper
{
public static byte[] Serialize(Person person)
{
using (MemoryStream memoryStream = new MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, person);
return memoryStream.ToArray();
}
}
public static Person Deserialize(byte[] bytes)
{
using (MemoryStream memoryStream = new MemoryStream(bytes))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
return (Person)binaryFormatter.Deserialize(memoryStream);
}
}
}
}
现在,你可以使用SerializationHelper
类中的Serialize
和Deserialize
方法对Person
结构体进行序列化和反序列化:
namespace SerializationExample
{
class Program
{
static void Main(string[] args)
{
Person person = new Person
{
Name = "John Doe",
Age = 30,
Address = "123 Main St"
};
// 序列化
byte[] serializedBytes = SerializationHelper.Serialize(person);
Console.WriteLine("Serialized bytes:");
foreach (byte b in serializedBytes)
{
Console.Write(b + " ");
}
Console.WriteLine();
// 反序列化
Person deserializedPerson = SerializationHelper.Deserialize(serializedBytes);
Console.WriteLine("\nDeserialized person:");
Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}, Address: {deserializedPerson.Address}");
}
}
}
这个示例将输出序列化后的字节数组和反序列化后的Person
结构体。