用 SerializableAttribute 标记 ISerializable 类型
更新:2007 年 11 月
TypeName |
MarkISerializableTypesWithSerializable |
CheckId |
CA2237 |
类别 |
Microsoft.Usage |
是否重大更改 |
否 |
原因
某外部可见的类型实现 System.Runtime.Serialization.ISerializable 接口,并且没有使用 System.SerializableAttribute 属性标记该类型。该规则忽略其基类型不可序列化的派生类型。
规则说明
要被公共语言运行时识别为可序列化,必须使用 SerializableAttribute 属性标记类型,即使该类型通过实现 ISerializable 接口使用了自定义的序列化例程。
如何修复冲突
要修复与该规则的冲突,请将 SerializableAttribute 属性应用于该类型。
何时禁止显示警告
不要禁止显示此规则发出的异常类警告,因为这些异常类必须是可序列化的才能在应用程序域之间正常工作。
示例
下面的示例演示一个与该规则冲突的类型。取消对 SerializableAttribute 属性行的注释可以满足该规则。
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);
}
}
}