CA2235:标记所有不可序列化的字段
类型名 |
MarkAllNonSerializableFields |
CheckId |
CA2235 |
类别 |
Microsoft.Usage |
是否重大更改 |
否 |
原因
在可以序列化的类型中声明了类型不可序列化的实例字段。
规则说明
可序列化类型是使用 System.SerializableAttribute 特性标记的类型。 当类型被序列化时,如果类型包含一个类型不可序列化的实例字段,则会引发 System.Runtime.Serialization.SerializationException 异常。
如何解决冲突
要修复与该规则的冲突,请将 System.NonSerializedAttribute 特性应用于不可序列化的字段。
何时禁止显示警告
只有当声明了允许序列化和反序列化字段实例的 System.Runtime.Serialization.ISerializationSurrogate 类型时,才能禁止显示此规则发出的警告。
示例
下面的示例演示一个与该规则冲突的类型和一个满足该规则的类型。
Imports System
Imports System.Runtime.Serialization
Namespace UsageLibrary
Public Class Mouse
Dim buttons As Integer
Dim scanTypeValue As String
ReadOnly Property NumberOfButtons As Integer
Get
Return buttons
End Get
End Property
ReadOnly Property ScanType As String
Get
Return scanTypeValue
End Get
End Property
Sub New(numberOfButtons As Integer, scanType As String)
buttons = numberOfButtons
scanTypeValue = 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
using System;
using System.Runtime.Serialization;
namespace UsageLibrary
{
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;
}
}
[SerializableAttribute]
public class InputDevices1
{
// Violates MarkAllNonSerializableFields.
Mouse opticalMouse;
public InputDevices1()
{
opticalMouse = new Mouse(5, "optical");
}
}
[SerializableAttribute]
public class InputDevices2
{
// Satisfies MarkAllNonSerializableFields.
[NonSerializedAttribute]
Mouse opticalMouse;
public InputDevices2()
{
opticalMouse = new Mouse(5, "optical");
}
}
}
相关规则
CA2236:对 ISerializable 类型调用基类方法