Share via


CA2235:必須標記所有不可序列化的欄位

屬性
規則識別碼 CA2235
標題 必須標記所有不可序列化的欄位
類別 使用方式
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 No

原因

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

檔案描述

可串行化類型是以 屬性標示的型別 System.SerializableAttribute 。 串行化類型時, System.Runtime.Serialization.SerializationException 如果類型包含無法串行化的 型別實例字段,而且 不會實作 介面,則會擲回例外狀況 System.Runtime.Serialization.ISerializable

提示

CA2235 不會針對實 ISerializable 作類型的實例字段引發,因為它們會提供自己的串行化邏輯。

如何修正違規

若要修正此規則的違規,請將 System.NonSerializedAttribute 屬性套用至無法串行化的欄位。

隱藏警告的時機

只有在宣告允許串行化和還原串行化欄位實例的類型時 System.Runtime.Serialization.ISerializationSurrogate ,才隱藏此規則的警告。

隱藏警告

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

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

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

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

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

範例

下列範例顯示兩種類型:一種違反規則,另一種符合規則。

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;
    }
}

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

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

[Serializable]
public class InputDevices2
{
    // Satisfies MarkAllNonSerializableFields.
    [NonSerialized]
    Mouse opticalMouse;

    public InputDevices2()
    {
        opticalMouse = new Mouse(5, "optical");
    }
}
Imports System
Imports System.Runtime.Serialization

Namespace ca2235

    Public Class Mouse

        ReadOnly Property NumberOfButtons As Integer

        ReadOnly Property ScanType As String

        Sub New(numberOfButtons As Integer, scanType As String)
            Me.NumberOfButtons = numberOfButtons
            Me.ScanType = 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

備註

規則 CA2235 不會分析實 ISerializable 作介面的類型(除非它們也會以 SerializableAttribute 屬性標示)。 這是因為規則 CA2237 已經建議使用 屬性來實作 介面的ISerializableSerializableAttribute標記類型。