ShouldSerialize 和 Reset 方法
ShouldSerialize 和 Reset 是您可以提供給屬性的選擇性方法,如果屬性沒有簡單的預設值。如果屬性具有簡單預設值,您應該代之以套用 DefaultValueAttribute,並提供預設值給屬性類別建構函式 (Constructor)。這些機制的任一個在設計工具中啟用下列功能。
如果屬性已被修改而與預設值不同,會在屬性瀏覽器中提供視覺的指示。
使用者可以在屬性上按一下滑鼠右鍵,並選擇 [重設] 來還原屬性為其預設值。
設計工具會產生較有效率的程式碼。
注意 若不套用 DefaultValueAttribute,就提供 ResetPropertyName 和 ShouldSerializePropertyName 方法。不要兩者都使用。
ResetPropertyName 方法設定屬性為其預設值,如下列程式碼片段所示。
Public Sub ResetMyFont()
MyFont = Nothing
End Sub
[C#]
public void ResetMyFont() {
MyFont = null;
}
注意 如果屬性沒有 Reset 方法、未加上 DefaultValueAttribute 標記,而且在宣告中沒有提供預設值,那麼在 Microsoft Visual Studio .NET 的 Windows Form 設計工具中,[屬性] 視窗的內容功能表中,這個屬性的 [重設] 選項將為停用。
設計工具 (例如 Visual Studio .NET) 會使用 ShouldSerializePropertyName 方法,檢查屬性的預設值是否已經變更,而且只要屬性變更,就會將程式碼寫入表單中,以便能更有效率地產生程式碼。例如:
'Returns true if the font has changed; otherwise, returns false.
' The designer writes code to the form only if true is returned.
Public Function ShouldSerializeMyFont() As Boolean
Return Not (thefont Is Nothing)
End Function
[C#]
// Returns true if the font has changed; otherwise, returns false.
// The designer writes code to the form only if true is returned.
public bool ShouldSerializeMyFont() {
return thefont != null;
}
完整程式碼範例如下。
Option Explicit
Option Strict
Imports System
Imports System.Windows.Forms
Imports System.Drawing
Public Class MyControl
Inherits Control
' Declare an instance of the Font class
' and set its default value to Nothing.
Private thefont As Font = Nothing
' The MyFont property.
Public Property MyFont() As Font
' Note that the Font property never
' returns null.
Get
If Not (thefont Is Nothing) Then
Return thefont
End If
If Not (Parent Is Nothing) Then
Return Parent.Font
End If
Return Control.DefaultFont
End Get
Set
thefont = value
End Set
End Property
Public Function ShouldSerializeMyFont() As Boolean
Return Not (thefont Is Nothing)
End Function
Public Sub ResetMyFont()
MyFont = Nothing
End Sub
End Class
[C#]
using System;
using System.Windows.Forms;
using System.Drawing;
public class MyControl : Control {
// Declare an instance of the Font class
// and set its default value to null.
private Font thefont = null;
// The MyFont property.
public Font MyFont {
// Note that the MyFont property never
// returns null.
get {
if (thefont != null) return thefont;
if (Parent != null) return Parent.Font;
return Control.DefaultFont;
}
set {
thefont = value;
}
}
public bool ShouldSerializeMyFont() {
return thefont != null;
}
public void ResetMyFont() {
MyFont = null;
}
}
在這個案例中,即使 MyFont
屬性所存取的私用變數值為 Null 參考 (Visual Basic 中的 Nothing),屬性瀏覽器也不會顯示 Null (Nothing);反而,它會顯示父代 (如果不為 Null 參考 (Nothing)) 的 Font 屬性或 Control 中定義的預設Font 值。因此 MyFont
預設值無法簡單設定,並且 DefaultValueAttribute 無法套用於這個屬性。相反地,ShouldSerialize 和 Reset 方法必須針對 MyFont
屬性來實作。