CA2236:对 ISerializable 类型调用基类方法
适用范围:Visual Studio
Visual Studio for Mac
Visual Studio Code
项 | “值” |
---|---|
RuleId | CA2236 |
Category | Microsoft.Usage |
重大更改 | 非中断 |
原因
类型派生自实现 System.Runtime.Serialization.ISerializable 接口的类型,并且满足以下条件之一:
该类型实现序列化构造函数(即具有 System.Runtime.Serialization.SerializationInfo、System.Runtime.Serialization.StreamingContext 参数签名的构造函数),但不调用基类型的序列化构造函数。
该类型实现 System.Runtime.Serialization.ISerializable.GetObjectData 方法,但不调用基类型的 GetObjectData 方法。
规则说明
在自定义序列化过程中,类型实现 GetObjectData 方法以序列化其字段,实现序列化构造函数以反序列化字段。 如果类型派生自实现 ISerializable 接口的类型,则应调用基类型 GetObjectData 方法和序列化构造函数方法来序列化/反序列化基类型的字段。 否则,将不会正确序列化和反序列化该类型。 请注意,如果派生类型未添加任何新字段,则该类型不需要实现 GetObjectData 方法或序列化构造函数,或调用基类型等效项。
如何解决冲突
若要修复与该规则的冲突,请从相应的派生类型方法或构造函数调用基类型 GetObjectData 方法或序列化构造函数。
何时禁止显示警告
不禁止显示此规则发出的警告。
示例
下面的示例演示了一个派生类型,通过调用序列化构造函数和基类型的 GetObjectData 方法满足规则。
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace UsageLibrary
{
[SerializableAttribute]
public class BaseType : ISerializable
{
int baseValue;
public BaseType()
{
baseValue = 3;
}
protected BaseType(
SerializationInfo info, StreamingContext context)
{
baseValue = info.GetInt32("baseValue");
}
[SecurityPermissionAttribute(SecurityAction.Demand,
SerializationFormatter = true)]
public virtual void GetObjectData(
SerializationInfo info, StreamingContext context)
{
info.AddValue("baseValue", baseValue);
}
}
[SerializableAttribute]
public class DerivedType : BaseType
{
int derivedValue;
public DerivedType()
{
derivedValue = 4;
}
protected DerivedType(
SerializationInfo info, StreamingContext context) :
base(info, context)
{
derivedValue = info.GetInt32("derivedValue");
}
[SecurityPermissionAttribute(SecurityAction.Demand,
SerializationFormatter = true)]
public override void GetObjectData(
SerializationInfo info, StreamingContext context)
{
info.AddValue("derivedValue", derivedValue);
base.GetObjectData(info, context);
}
}
}