在C#中,序列化是将对象的状态信息转换为可以存储或传输的格式的过程。以下是实现C#序列化的几种方法:
BinaryFormatter
类进行序列化:using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
Person person = new Person { Name = "John", Age = 30 };
// 序列化
using (FileStream fileStream = new FileStream("person.bin", FileMode.Create))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(fileStream, person);
}
}
}
JsonConvert
类进行序列化(需要安装Newtonsoft.Json库):using System;
using Newtonsoft.Json;
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
Person person = new Person { Name = "John", Age = 30 };
// 序列化
string json = JsonConvert.SerializeObject(person);
Console.WriteLine(json);
}
}
XmlSerializer
类进行序列化:using System;
using System.IO;
using System.Xml.Serialization;
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
Person person = new Person { Name = "John", Age = 30 };
// 序列化
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Person));
using (StringWriter stringWriter = new StringWriter())
{
xmlSerializer.Serialize(stringWriter, person);
string xml = stringWriter.ToString();
Console.WriteLine(xml);
}
}
}
以上示例展示了如何使用不同的方法对C#对象进行序列化。注意,在使用这些方法时,需要确保对象及其属性具有可序列化的特性。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。