在C#中,对象的序列化是将对象转换为可以存储或传输的格式的过程。当对象被序列化后,它可以被保存到文件中,传输到其他应用程序或者通过网络发送。C#提供了几种不同的方式来实现对象的序列化,下面是一些常用的方法:
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class MyClass
{
public int MyProperty { get; set; }
}
class Program
{
static void Main()
{
MyClass obj = new MyClass { MyProperty = 42 };
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream stream = new FileStream("data.bin", FileMode.Create))
{
formatter.Serialize(stream, obj);
}
}
}
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
[DataContract]
public class MyClass
{
[DataMember]
public int MyProperty { get; set; }
}
class Program
{
static void Main()
{
MyClass obj = new MyClass { MyProperty = 42 };
DataContractSerializer serializer = new DataContractSerializer(typeof(MyClass));
using (FileStream stream = new FileStream("data.xml", FileMode.Create))
{
using (XmlWriter writer = XmlWriter.Create(stream))
{
serializer.WriteObject(writer, obj);
}
}
}
}
using System;
using Newtonsoft.Json;
public class MyClass
{
public int MyProperty { get; set; }
}
class Program
{
static void Main()
{
MyClass obj = new MyClass { MyProperty = 42 };
string json = JsonConvert.SerializeObject(obj);
Console.WriteLine(json);
}
}
以上是几种常用的对象序列化方法,在实际应用中可以根据具体需求选择合适的方法。