CA2235: Označte všechna neserializovatelná pole
TypeName |
MarkAllNonSerializableFields |
CheckId |
CA2235 |
Kategorie |
Microsoft.Usage |
Narušující změna |
Nenarušující |
Příčina
Neserializovatelný typ pole instance je deklarován v serializovatelném typu.
Popis pravidla
Serializovatelný typ je takový, který je označen atributem SerializableAttribute.Při serializaci typu je vyvolána výjimka SerializationException, pokud typ obsahuje pole instance neserializovatelného typu.
Jak vyřešit porušení
Chcete-li opravit porušení tohoto pravidla, použijte atribut NonSerializedAttribute na pole, které není serializovatelné.
Kdy potlačit upozornění
Upozornění tohoto pravidla lze potlačit pouze, pokud je deklarován typ ISerializationSurrogate, který umožňuje serializaci instancí polí.
Příklad
Následující příklad znázorňuje typ porušující toto pravidlo a typ, který toto pravidlo splňuje.
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");
}
}
}
Související pravidla
CA2236: Volejte metody třídy Base na typech ISerializable
CA2240: Implementujte správně ISerializable
CA2229: Implementovat serializační konstruktory
CA2238: Implementujte správně metody serializace
CA2237: Označte typy ISerializable pomocí SerializableAttribute