CA2237:用 SerializableAttribute 标记 ISerializable 类型

属性
规则 ID CA2237
标题 用 SerializableAttribute 标记 ISerializable 类型
类别 使用情况
修复是中断修复还是非中断修复 非中断
在 .NET 8 中默认启用

原因

外部可见类型实现 System.Runtime.Serialization.ISerializable 接口,且该类型没有使用 System.SerializableAttribute 属性进行标记。 此规则会忽略基类型无法序列化的派生类型。

规则说明

若要被公共语言运行时识别为可序列化,类型必须用 SerializableAttribute 属性进行标记,即使该类型通过实现 ISerializable 接口使用自定义序列化例程也是如此。

如何解决冲突

若要解决此规则的冲突,请将 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);
    }
}