CA2237:ISerializable 類型必須標記 SerializableAttribute

屬性
規則識別碼 CA2237
標題 ISerializable 類型必須標記 SerializableAttribute
類別 使用方式
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 No

原因

外部可見型別會實作 介面, System.Runtime.Serialization.ISerializable 而且型別不會以 System.SerializableAttribute 屬性標示。 此規則會忽略基底類型無法序列化的衍生型別。

檔案描述

若要讓 Common Language Runtime 辨識為可序列化,即使類型透過 介面的 ISerializable 實作使用自訂序列化常式,類型也必須以 屬性標示 SerializableAttribute

如何修正違規

若要修正此規則的違規,請將 SerializableAttribute 屬性套用至類型。

隱藏警告的時機

請勿針對例外狀況類別隱藏此規則的警告,因為它們必須可序列化,才能跨應用程式域正常運作。

隱藏警告

如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。

#pragma warning disable CA2237
// The code that's violating the rule is on this line.
#pragma warning restore CA2237

若要停用檔案、資料夾或專案的規則,請在組態檔 中將其嚴重性設定為 。 none

[*.{cs,vb}]
dotnet_diagnostic.CA2237.severity = none

如需詳細資訊,請參閱 如何隱藏程式碼分析警告

範例

下列範例顯示違反規則的型別。 取消 SerializableAttribute 批註屬性行以符合規則。

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

Namespace ca2237

    ' <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

        Overridable Sub GetObjectData(
         info As SerializationInfo, context As StreamingContext) _
         Implements ISerializable.GetObjectData

            info.AddValue("baseValue", baseValue)

        End Sub

    End Class

End Namespace
// [SerializableAttribute]
public class BaseType : ISerializable
{
    int baseValue;

    public BaseType()
    {
        baseValue = 3;
    }

    protected BaseType(
       SerializationInfo info, StreamingContext context)
    {
        baseValue = info.GetInt32("baseValue");
    }

    public virtual void GetObjectData(
       SerializationInfo info, StreamingContext context)
    {
        info.AddValue("baseValue", baseValue);
    }
}