gpt4 book ai didi

c# - 在 C# 中序列化和反序列化自定义异常

转载 作者:行者123 更新时间:2023-12-05 05:46:21 27 4
gpt4 key购买 nike

我目前正在处理异常,我已经创建了一个实现父异常类的自定义异常。

当我尝试对此类自定义异常进行序列化或反序列化时出现问题。

错误如下:“System.Runtime.Serialization.SerializationException: 'Member 'InnerException' was not found.'”

我引用了互联网上的许多资源,但无法解决问题。我将代码附加到此正文中。

[Serializable]
public class CustomException : Exception
{
public const string DefaultExceptionDescription = "temp";

public string ExceptionDescription { get; set; }

public string ReferenceId { get; private set; } = "temp";

public CustomException(string ExceptionDescription = DefaultExceptionDescription)
{
ExceptionDescription = ExceptionDescription;
}

[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
protected CustomException(SerializationInfo info, StreamingContext context) : base(info, context)
{
if (info != null)
{
ExceptionDescription = info.GetString(nameof(ExceptionDescription));
ReferenceId = info.GetString(nameof(ReferenceId));
}
}

[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info != null)
{
info.AddValue(nameof(ExceptionDescription), ExceptionDescription);
info.AddValue(nameof(ReferenceId), ReferenceId);
}

base.GetObjectData(info, context);
}
}

提前致谢!!!

最佳答案

The common language runtime throws SerializationException if any type in the graph of objects being serialized does not have the SerializableAttribute attribute applied.

此处:https://learn.microsoft.com/en-us/dotnet/api/system.serializableattribute?view=net-6.0#remarks

尝试删除 SerializableAttribute

关于c# - 在 C# 中序列化和反序列化自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71206290/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com