CA2237: Označte typy ISerializable pomocí SerializableAttribute
TypeName |
MarkISerializableTypesWithSerializable |
CheckId |
CA2237 |
Kategorie |
Microsoft.Usage |
Narušující změna |
Nenarušující |
Příčina
Externě viditelný typ implementuje rozhraní ISerializable a typ není označen atributem SerializableAttribute.Pravidlo ignoruje odvozené typy, jejichž základní typ není serializovatelný.
Popis pravidla
Aby modul runtime rozeznal typ jako serializovatelný, musí být označen atributem SerializableAttribute, i pokud typ používání vlastní serializační rutinu skrze implementaci rozhraní ISerializable.
Jak vyřešit porušení
Pro opravu porušení toho pravidla, je nutné typu přidat atribut SerializableAttribute.
Kdy potlačit upozornění
Není vhodné potlačovat upozornění tohoto pravidla pro třídy výjimek, protože musí být serializovatelné, aby mohly správně pracovat mezi aplikačními doménami.
Příklad
Následující příklad ukazuje typ, který toto pravidlo porušuje.Odkomentujte řádek s atributem SerializableAttribute pro splnění pravidla.
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);
}
}
}
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
CA2235: Označte všechna neserializovatelná pole