共用方式為


請標記所有不可序列化的欄位

更新:2007 年 11 月

型別名稱

MarkAllNonSerializableFields

CheckId

CA2235

分類

Microsoft.Usage

中斷變更

非中斷

原因

可序列化之型別中所宣告之型別的執行個體 (Instance) 欄位是不可序列化的。

規則描述

可序列化型別是以 System.SerializableAttribute 屬性 (Attribute) 標示的型別。當型別序列化時,如果型別所包含的不是可序列化之型別的執行個體欄位,將會發生 System.Runtime.Serialization.SerializationException 例外狀況。

如何修正違規

若要修正此規則的違規情形,請將 System.NonSerializedAttribute 屬性套用到不可序列化的欄位。

隱藏警告的時機

只有在宣告的 System.Runtime.Serialization.ISerializationSurrogate 型別允許欄位的執行個體成為序列化或還原序列化時,才能隱藏這項規則的警告。

範例

下列範例會顯示違反規則的型別和滿足規則的型別。

Imports System
Imports System.Runtime.Serialization

Namespace UsageLibrary

   Public Class Mouse

      Dim buttons As Integer
      Dim scanTypeValue As String

      ReadOnly Property NumberOfButtons As Integer
         Get
            Return buttons
         End Get
      End Property

      ReadOnly Property ScanType As String
         Get
            Return scanTypeValue
         End Get
      End Property

      Sub New(numberOfButtons As Integer, scanType As String)
         buttons = numberOfButtons
         scanTypeValue = scanType
      End Sub

   End Class

   <SerializableAttribute> _ 
   Public Class InputDevices1

      ' Violates MarkAllNonSerializableFields.
      Dim opticalMouse As Mouse 

      Sub New()
         opticalMouse = New Mouse(5, "optical") 
      End Sub

   End Class

   <SerializableAttribute> _ 
   Public Class InputDevices2

      ' Satisfies MarkAllNonSerializableFields.
      <NonSerializedAttribute> _ 
      Dim opticalMouse As Mouse 

      Sub New()
         opticalMouse = New Mouse(5, "optical") 
      End Sub

   End Class

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

namespace UsageLibrary
{
   public class Mouse
   {
      int buttons;
      string scanTypeValue;

      public int NumberOfButtons
      {
         get { return buttons; }
      }

      public string ScanType
      {
         get { return scanTypeValue; }
      }

      public Mouse(int numberOfButtons, string scanType)
      {
         buttons = numberOfButtons;
         scanTypeValue = scanType;
      }
   }

   [SerializableAttribute]
   public class InputDevices1
   {
      // Violates MarkAllNonSerializableFields.
      Mouse opticalMouse;

      public InputDevices1()
      {
         opticalMouse = new Mouse(5, "optical"); 
      }
   }

   [SerializableAttribute]
   public class InputDevices2
   {
      // Satisfies MarkAllNonSerializableFields.
      [NonSerializedAttribute]
      Mouse opticalMouse;

      public InputDevices2()
      {
         opticalMouse = new Mouse(5, "optical"); 
      }
   }
}

相關規則

請呼叫 ISerializable 型別上的基底類別方法

請正確實作 ISerializable

請實作序列化建構函式

請正確實作序列化方法

請以 SerializableAttribute 標記 ISerializable 型別

為選擇性欄位提供還原序列化方法

請保護序列化建構函式