c#

c# struct怎样进行序列化

小樊
82
2024-11-26 14:08:23
栏目: 编程语言

在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类中的SerializeDeserialize方法对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结构体。

0
看了该问题的人还看了