序列化是一种将对象转换为可存储或传输的格式的过程。在.NET中,序列化通常涉及到将对象转换为字节流,以便在网络上发送或将其存储到磁盘上。以下是在.NET中运行序列化的一些方法:
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void Serialize(Person person, string fileName)
{
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream stream = new FileStream(fileName, FileMode.Create))
{
formatter.Serialize(stream, person);
}
}
public static Person Deserialize(string fileName)
{
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
return (Person)formatter.Deserialize(stream);
}
}
using System.IO;
using System.Xml.Serialization;
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void Serialize(Person person, string fileName)
{
XmlSerializer serializer = new XmlSerializer(typeof(Person));
using (FileStream stream = new FileStream(fileName, FileMode.Create))
{
serializer.Serialize(stream, person);
}
}
public static Person Deserialize(string fileName)
{
XmlSerializer serializer = new XmlSerializer(typeof(Person));
using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
return (Person)serializer.Deserialize(stream);
}
}
using System.IO;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
[DataContract]
public class Person
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
}
public static void Serialize(Person person, string fileName)
{
DataContractSerializer serializer = new DataContractSerializer(typeof(Person));
using (FileStream stream = new FileStream(fileName, FileMode.Create))
{
serializer.WriteObject(stream, person);
}
}
public static Person Deserialize(string fileName)
{
DataContractSerializer serializer = new DataContractSerializer(typeof(Person));
using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
return (Person)serializer.ReadObject(stream);
}
}
在选择序列化方式时,需要根据具体的需求和场景进行选择。
领取专属 10元无门槛券
手把手带您无忧上云