C# 序列化 反序列化
/// <summary> /// 序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> private static byte[]? Serialize<T>(T? obj) { if (obj == null) return default; using var memoryStream = new MemoryStream(); DataContractSerializer ser = new(typeof(T)); ser.WriteObject(memoryStream, obj); var data = memoryStream.ToArray(); return data; } /// <summary> /// 反序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data"></param> /// <returns></returns> private static T? Deserialize<T>(byte[]? data) { if (data == null) return default; using var memoryStream = new MemoryStream(data); XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, new XmlDictionaryReaderQuotas()); DataContractSerializer ser = new(typeof(T)); var result = (T?)ser.ReadObject(reader, true); return result; }