序列化与反序列化,当对象用来传输

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;

namespace CodeArt.SharePoint
{
/// <summary>
/// 对象序列化
/// </summary>
public static class SerializeUtil
{
/// <summary>
/// 将对象序列化成xml
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string Seralize(object obj)
{
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(obj.GetType());

MemoryStream s = new MemoryStream();
XmlTextWriter w = new XmlTextWriter(s, Encoding.UTF8);

//xs.Serialize(w, o, ns);

xs.Serialize(w, obj);

string xmlData = Encoding.UTF8.GetString(s.ToArray()).Trim();

return xmlData;
}

/// <summary>
/// 将xml反序列化成某个对象
/// </summary>
/// <param name="t"></param>
/// <param name="xml"></param>
/// <returns></returns>
public static object Deserialize(Type t, string xml)
{
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer( t );

System.IO.StringReader sw = new System.IO.StringReader(xml);

return xs.Deserialize(sw) ;
}
}
}

当一个类的信息要用来传输,只需要在类的顶部加上[Serialize],那么这个类就可以序列化了,并且可以用在页面传值

 

posted on 2012-04-08 23:00  gzh4455  阅读(213)  评论(0编辑  收藏  举报