更具体地说,当异常包含自定义对象时,这些自定义对象本身可以是自身可序列化的
举个例子:
public class MyException : Exception
{
private readonly string resourceName;
private readonly IList<string> validationErrors;
public MyException(string resourceName, IList<string> validationErrors)
{
this.resourceName = resourceName;
this.validationErrors = validationErrors;
}
public string ResourceName
{
get { return this.resourceName; }
}
public IList<string> ValidationErrors
{
get { return this.validationErrors; }
}
}
Run Code Online (Sandbox Code Playgroud)
如果此异常序列化和反序列化,则不会保留两个自定义属性(ResourceName和ValidationErrors).属性将返回null.
是否有用于实现自定义异常序列化的通用代码模式?
对于以下异常实现,SonarCube 显示错误“更新‘ISerializable’的这个实现以符合推荐的序列化模式”:
[Serializable]
public class UnrecoverableException : Exception, ISerializable
{
public bool Ignore { get; }
public UnrecoverableException()
{
}
public UnrecoverableException(string message, Exception innerException)
: base(message, innerException)
{
}
protected UnrecoverableException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
Ignore= info.GetBoolean(nameof(Ignore));
}
public UnrecoverableException(string message, bool ignore= false) : base(message)
{
Ignore= ignore;
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(nameof(Ignore), Ignore);
base.GetObjectData(info, context);
}
}
Run Code Online (Sandbox Code Playgroud)
不知道这里有什么问题对我来说似乎完全遵循这里描述的规则https://rules.sonarsource.com/csharp/tag/pitfall/RSPEC-3925
此规则在
ISerializable不遵循 Microsoft 推荐的序列化模式的情况下实现的类型会引发问题。
System.SerializableAttribute缺少该属性。不可序列化的字段没有用该 …