本文共 1908 字,大约阅读时间需要 6 分钟。
在网上很多人说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()
{
ListpeopleList = new List
{
new People{Name = "张三", Sex = "男"},
new People{Name = "李四", Sex = "女"},
};
XmlSerializer xs = new XmlSerializer(typeof(List));
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));
Stream stream = new FileStream("C:\\zzl.XML", FileMode.Open,
FileAccess.Read, FileShare.Read);
ListpeopleList = xs.Deserialize(stream) as List ;
if (peopleList != null) peopleList.ForEach(i =>
Console.WriteLine(i.Name.PadRight(10) + i.Sex));
stream.Close();
}
#endregion
}
///
/// 人类
///
[Serializable]
public class People
{
///
/// 姓名
///
public string Name { get; set; }
///
/// 性别
///
public string Sex { get; set; }
}
}
,如需转载请自行联系原博主。