LIST<T>现在也支持序列化和反序列化了
在网上很多人说XML的序列化不支持泛型,今天有时间,去做了一个测试,测试环境是.net framework4.0,测试结果是可以被序列化和反序列化。
namespace List可以被序列化
{
class Program
{
static void Main(string[] args)
{
SerializeNow();
DeSerializeNow();
XmlSerialize();
XmlDeserialize();
Console.ReadKey();
}
#region 二进制序列化
public static void SerializeNow()
{
People people = new People { Name = "zzl", Sex = "男" };
FileStream fileStream = new FileStream("c:\\temp.dat", FileMode.Create);
BinaryFormatter b = new BinaryFormatter();
b.Serialize(fileStream, people);
fileStream.Close();
}
public static void DeSerializeNow()
{
People people = new People();
FileStream fileStream = new FileStream("c:\\temp.dat", FileMode.Open,
FileAccess.Read, FileShare.Read);
BinaryFormatter b = new BinaryFormatter();
people = b.Deserialize(fileStream) as People;
if (people != null) Console.WriteLine(people.Name.PadRight(10) + people.Sex);
fileStream.Close();
}
#endregion
#region XML序列化 (XML序列化不支持泛型。你需要自行序列化到数组再复制到泛型集合)
public static void XmlSerialize()
{
List<People> peopleList = new List<People>
{
new People{Name = "张三", Sex = "男"},
new People{Name = "李四", Sex = "女"},
};
XmlSerializer xs = new XmlSerializer(typeof(List<People>));
Stream stream = new FileStream("c:\\zzl.XML", FileMode.Create,
FileAccess.Write, FileShare.Read);
xs.Serialize(stream, peopleList);
stream.Close();
}
public static void XmlDeserialize()
{
XmlSerializer xs = new XmlSerializer(typeof(List<People>));
Stream stream = new FileStream("C:\\zzl.XML", FileMode.Open,
FileAccess.Read, FileShare.Read);
List<People> peopleList = xs.Deserialize(stream) as List<People>;
if (peopleList != null) peopleList.ForEach(i =>
Console.WriteLine(i.Name.PadRight(10) + i.Sex));
stream.Close();
}
#endregion
}
/// <summary>
/// 人类
/// </summary>
[Serializable]
public class People
{
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 性别
/// </summary>
public string Sex { get; set; }
}
}
分类:
其它 / ASP.NET
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏