Share via


CA2237:以 SerializableAttribute 标记 ISerializable 类型

类型名

MarkISerializableTypesWithSerializable

CheckId

CA2237

类别

Microsoft.Usage

是否重大更改

原因

某外部可见的类型实现 System.Runtime.Serialization.ISerializable 接口,并且没有使用 System.SerializableAttribute 特性标记该类型。 该规则忽略其基类型不可序列化的派生类型。

规则说明

要被公共语言运行时识别为可序列化,必须使用 SerializableAttribute 特性标记类型,即使该类型通过实现 ISerializable 接口使用了自定义的序列化例程。

如何解决冲突

要修复与该规则的冲突,请将 SerializableAttribute 特性应用于该类型。

何时禁止显示警告

不要禁止显示此规则发出的异常类警告,因为这些异常类必须是可序列化的才能在应用程序域之间正常工作。

示例

下面的示例演示一个与该规则冲突的类型。 取消对 SerializableAttribute 特性行的注释可以满足该规则。

Imports System
Imports System.Runtime.Serialization
Imports System.Security.Permissions

Namespace UsageLibrary

   ' <SerializableAttribute> _ 
   Public Class BaseType
      Implements ISerializable

      Dim baseValue As Integer

      Sub New()
         baseValue = 3
      End Sub

      Protected Sub New( _ 
         info As SerializationInfo, context As StreamingContext)

         baseValue = info.GetInt32("baseValue")

      End Sub

      <SecurityPermissionAttribute(SecurityAction.Demand, _ 
          SerializationFormatter := True)> _ 
      Overridable Sub GetObjectData( _ 
         info As SerializationInfo, context As StreamingContext) _ 
         Implements ISerializable.GetObjectData

         info.AddValue("baseValue", baseValue)

      End Sub

   End Class

End Namespace
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);
      }
   }
}

相关规则

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

CA2240:正确实现 ISerializable

CA2229:实现序列化构造函数

CA2238:正确实现序列化方法

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

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

CA2120:保护序列化构造函数