다음을 통해 공유


Implement serialization methods correctly

TypeName

ImplementSerializationMethodsCorrectly

CheckId

CA2238

Category

Microsoft.Usage

Breaking Change

Breaking,NonBreaking

Cause

A method that handles a serialization event does not have the correct signature, return type, or visibility.

Rule Description

A method is designated a serialization event handler by applying one of the following serialization event attributes:

Serialization event handlers take a single parameter of type System.Runtime.Serialization.StreamingContext, return void, and have private visibility.

How to Fix Violations

To fix a violation of this rule, correct the signature, return type, or visibility of the serialization event handler.

When to Exclude Warnings

Do not exclude a warning from this rule.

Example

The following example shows correctly declared serialization event handlers.

Imports System
Imports System.Runtime.Serialization

Namespace UsageLibrary

   <SerializableAttribute> _ 
   Public Class SerializationEventHandlers

      <OnSerializingAttribute> _ 
      Private Sub OnSerializing(context As StreamingContext) 
      End Sub

      <OnSerializedAttribute> _ 
      Private Sub OnSerialized(context As StreamingContext) 
      End Sub

      <OnDeserializingAttribute> _ 
      Private Sub OnDeserializing(context As StreamingContext)
      End Sub

      <OnDeserializedAttribute> _ 
      Private Sub OnDeserialized(context As StreamingContext)
      End Sub

   End Class

End Namespace
using System;
using System.Runtime.Serialization;

namespace UsageLibrary
{
   [SerializableAttribute]
   public class SerializationEventHandlers
   {
      [OnSerializingAttribute]
      void OnSerializing(StreamingContext context) {}

      [OnSerializedAttribute]
      void OnSerialized(StreamingContext context) {}

      [OnDeserializingAttribute]
      void OnDeserializing(StreamingContext context) {}

      [OnDeserializedAttribute]
      void OnDeserialized(StreamingContext context) {}
   }
}

Call base class methods on ISerializable types

Implement ISerializable correctly

Implement serialization constructors

Mark all non-serializable fields

Mark ISerializable types with serializable

Provide deserialization methods for optional fields

Secure GetObjectData overrides

Secure serialization constructors