在C#中,可以使用序列化来保存数据集中的对象列表。序列化是将对象转换为字节流的过程,以便将其保存到文件或传输到其他系统。C#提供了多种序列化的方式,包括二进制序列化、XML序列化和JSON序列化。
using System;
using System.Collections.Generic;
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(string[] args)
{
List<Person> personList = new List<Person>
{
new Person { Name = "Alice", Age = 25 },
new Person { Name = "Bob", Age = 30 }
};
// 创建文件流并将对象列表序列化到文件
using (FileStream fs = new FileStream("data.bin", FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, personList);
}
Console.WriteLine("对象列表已序列化并保存到文件。");
}
}
using System;
using System.Collections.Generic;
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(string[] args)
{
List<Person> personList = new List<Person>
{
new Person { Name = "Alice", Age = 25 },
new Person { Name = "Bob", Age = 30 }
};
// 创建文件流并将对象列表序列化为XML并保存到文件
using (StreamWriter sw = new StreamWriter("data.xml"))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Person>));
serializer.Serialize(sw, personList);
}
Console.WriteLine("对象列表已序列化并保存到文件。");
}
}
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
// 定义一个示例类
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Person> personList = new List<Person>
{
new Person { Name = "Alice", Age = 25 },
new Person { Name = "Bob", Age = 30 }
};
// 创建文件流并将对象列表序列化为JSON并保存到文件
using (StreamWriter sw = new StreamWriter("data.json"))
{
string json = JsonConvert.SerializeObject(personList);
sw.Write(json);
}
Console.WriteLine("对象列表已序列化并保存到文件。");
}
}
以上是在C#中保存数据集中的对象列表的几种常见方法。根据实际需求和场景选择适合的序列化方式,并根据需要选择合适的文件格式(二进制、XML或JSON)。
领取专属 10元无门槛券
手把手带您无忧上云