序列化是将对象转换为一种格式,以便在需要时可以将其反序列化为原始对象。C#中使用以下三种方式进行序列化和反序列化:
-
BinaryFormatter类:将对象序列化为二进制格式,是.NET中最常用的序列化方式,可以将序列化后的数据存储到磁盘、内存或网络中。
-
XmlSerializer类:将对象序列化为XML格式,适合在不同平台间传输数据。
-
ISerializable接口:通过实现ISerializable接口,在序列化和反序列化过程中,控制对象的序列化行为。
以下是使用上述三种方式进行序列化和反序列化的示例:
BinaryFormatter类示例:
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.Name = "Tom";
person.Age = 20;
//序列化
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, person);
byte[] data = stream.ToArray();
//反序列化
stream = new MemoryStream(data);
person = formatter.Deserialize(stream) as Person;
Console.WriteLine($"Name:{person.Name} Age:{person.Age}");
}
}
XmlSerializer类示例:
using System;
using System.IO;
using System.Xml.Serialization;
[Serializable]
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.Name = "Tom";
person.Age = 20;
//序列化
XmlSerializer serializer = new XmlSerializer(typeof(Person));
StringWriter writer = new StringWriter();
serializer.Serialize(writer, person);
string xml = writer.ToString();
//反序列化
StringReader reader = new StringReader(xml);
person = serializer.Deserialize(reader) as Person;
Console.WriteLine($"Name:{person.Name} Age:{person.Age}");
}
}
ISerializable接口示例:
using System;
using System.IO;
using System.Runtime.Serialization;
[Serializable]
class Person : ISerializable
{
public string Name { get; set; }
public int Age { get; set; }
public Person() { }
public Person(SerializationInfo info, StreamingContext context)
{
Name = info.GetString("Name");
Age = info.GetInt32("Age");
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Name", Name);
info.AddValue("Age", Age);
}
}
class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.Name = "Tom";
person.Age = 20;
//序列化
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, person);
byte[] data = stream.ToArray();
//反序列化
stream = new MemoryStream(data);
person = formatter.Deserialize(stream) as Person;
Console.WriteLine($"Name:{person.Name} Age:{person.Age}");
}
}
上述三种示例均展示了对象序列化和反序列化的基本操作,并对这三种方式进行了比较。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#使用BinaryFormatter类、ISerializable接口、XmlSerializer类进行序列化和反序列化 - Python技术站