获取任意可序列化对象的Xml字符串,方便在日志中查看任一所感兴趣的对象。
代码:
public static string GetLoggingString(this object obj) { using (var stream = new MemoryStream()) { new XmlSerializer(obj.GetType()).Serialize(stream, obj); stream.Position = 0; var buffer = new byte[stream.Length]; stream.ReadAsync(buffer, 0, buffer.Length); stream.FlushAsync(); return Encoding.UTF8.GetString(buffer); } }
用法:
var list = new List<string> { "abs", "sdf", "srer" }; var d = list.GetLoggingString();
结果:
<?xml version="1.0"?> <ArrayOfString xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <string>abs</string> <string>sdf</string> <string>srer</string> </ArrayOfString>