在C#中序列化Exception对象,可以使用以下方法:
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public static class ExceptionExtensions
{
public static byte[] Serialize(this Exception exception)
{
using var memoryStream = new MemoryStream();
var binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, exception);
return memoryStream.ToArray();
}
public static Exception Deserialize(this byte[] serializedException)
{
using var memoryStream = new MemoryStream(serializedException);
var binaryFormatter = new BinaryFormatter();
return (Exception)binaryFormatter.Deserialize(memoryStream);
}
}
using System;
using System.IO;
using System.Runtime.Serialization;
public static class ExceptionExtensions
{
public static byte[] Serialize(this Exception exception)
{
using var memoryStream = new MemoryStream();
var dataContractSerializer = new DataContractSerializer(typeof(Exception));
dataContractSerializer.WriteObject(memoryStream, exception);
return memoryStream.ToArray();
}
public static Exception Deserialize(this byte[] serializedException)
{
using var memoryStream = new MemoryStream(serializedException);
var dataContractSerializer = new DataContractSerializer(typeof(Exception));
return (Exception)dataContractSerializer.ReadObject(memoryStream);
}
}
using System;
using Newtonsoft.Json;
public static class ExceptionExtensions
{
public static string Serialize(this Exception exception)
{
return JsonConvert.SerializeObject(exception);
}
public static Exception Deserialize(this string serializedException)
{
return JsonConvert.DeserializeObject<Exception>(serializedException);
}
}
以上三种方法都可以实现Exception对象的序列化和反序列化,可以根据具体需求选择合适的方法。
领取专属 10元无门槛券
手把手带您无忧上云