LIST<T>序列化和反序列化
2012-09-06 09:09
375 查看
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; }
}
}
分
相关文章推荐
- 支持vector,map,list<map>序列化,反序列化实现
- 对象(List<T>)的序列化和反序列化
- android关于序列化和反序列化List<? implement Parcelable> list属性
- .Net List<obj> 序列化和反序列化
- C# 序列化反序列化 list<>
- LIST<T>现在也支持序列化和反序列化了
- LIST<T>现在也支持序列化和反序列化了
- .Net:反序列化处理Json字符串.转换成List<T>类型
- table 的form序列化提交 ,及json 处理list<对象>
- List<T>到XML的序列化与反序列化
- List 序列化与反序列化到struts2的<s:hidden>变量
- WCF传输List<object>时序列化问题
- WCF学习笔记(5)——wcf序列化List&lt;T&gt;并返回
- 在Unity序列化List<>
- Json串与List<Bean>、Bean之间的转换,处理类中List<Bean>属性的序列化问题
- 关于hibernate中实体类为什么尽量序列化和类似<s:checkboxlist/>标签
- WCF学习笔记(5)——wcf序列化List<T>并返回
- WCF传输List<object>时序列化问题
- 深度剖析C#序列化和反序列化<转载>
- 序列化 Activity之间进行数据传输 List<Object> Parcelable serializable两种方式