Unity-Serialize

Unity-Serialize

XMLSerializer

C#序列化对象为XML条件:

  • 对于类,要使其实例可以序列化,必须保证其自己、成员以及父类都有[Serializable]标记
  • 对象数组序列化时,无参构造函数不可少

XML序列化

1
2
3
4
5
6
7
8
public static string XMLSerialize<T>(T entity)
{
StringBuilder buffer = new StringBuilder();
XmlSerializer serializer = new XmlSerializer(typeof(T));
TextWriter writer = new StringWriter(buffer);
serializer.Serialize(writer, entity);
return buffer.ToString();
}

XML反序列化

1
2
3
4
5
6
7
8
9
10
11
12
13
public static T DeXMLSerialize<T>(string xmlString)
{
StringBuilder buffer = new StringBuilder();
buffer.Append(xmlString);
XmlSerializer serializer = new XmlSerializer(typeof(T));

TextReader reader = new StringReader(buffer.ToString());

object obj = serializer.Deserialize(reader);
T cloneObject = (T)obj;

return cloneObject;
}

Unity-Serialize
http://example.com/2023/01/10/Unity-Serialize/
作者
Chen Shuwen
发布于
2023年1月10日
许可协议