CA2236:对 ISerializable 类型调用基类方法

适用范围:yesVisual Studio noVisual Studio for Mac noVisual Studio Code

“值”
RuleId CA2236
Category Microsoft.Usage
重大更改 非中断

原因

类型派生自实现 System.Runtime.Serialization.ISerializable 接口的类型,并且满足以下条件之一:

规则说明

在自定义序列化过程中,类型实现 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);
      }
   }
}

CA2240:正确实现 ISerializable

CA2229:实现序列化构造函数

CA2238:正确实现序列化方法

CA2235:标记所有不可序列化的字段

CA2237:用 SerializableAttribute 标记 ISerializable 类型

CA2239:为可选字段提供反序列化方法

CA2120:保护序列化构造函数