标题: C#序列化总结 [打印本页] 作者: Adam丶鱼 时间: 2020-6-7 18:51 标题: C#序列化总结 public class XMLUtil
{
/// <summary>
/// XML & Datacontract Serialize & Deserialize Helper
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="serialObject"></param>
/// <returns></returns>
public static string Serializer<T>(T serialObject) where T : class
{
string result = string.Empty;
using (MemoryStream mem = new MemoryStream())
{
using (XmlTextWriter writer = new XmlTextWriter(mem, Encoding.UTF8))
{
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));
ser.Serialize(writer, serialObject);
result = Encoding.UTF8.GetString(mem.ToArray());
}
}
return result;
}
public static T Deserialize<T>(string str) where T : class
{
T result = null;
using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(str)))
{
using (StreamReader streamReader = new StreamReader(memoryStream))
{
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
result = (T)xmlSerializer.Deserialize(memoryStream);
}
}
return result;
}
}