在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);
}
}
以上是幾種常用的對象序列化方法,在實際應用中可以根據具體需求選擇合適的方法。