因為我們正在指派用於繪製輪廓的筆,因此需要使用 using 或 Try/Finally 和 Dispose 以確保迅速釋放 Windows 筆對象。(同樣,如果非常確信所調用的方法不會引發異常,可以在完成筆的處理後,跳過異常處理,而只調用 Dispose。但我們必須調用 Dispose,無論是直接調用,還是通過 using 語句。
實現 Fill 方法
Fill 方法很簡單:指派一個畫筆,然後在螢幕上填充對象 -- 並確保 Dispose 畫筆。
繪圖對象的容器
因為要重複繪製我們的對象(在 Windows 表單版本中,每次都將繪製映像;在 ASP.NET 版本中,每次都將重新載入 Web 頁),因此需要將它們放在一個容器中,以便能夠反覆訪問它們。
Dr. GUI 更進一步,將容器變得智能化,使其知道如何繪製所包含的對象。以下是這個容器類的 C# 代碼:
C#
public class DShapeList {
ArrayList wholeList = new ArrayList();
ArrayList filledList = new ArrayList();
public void Add(DShape d) {
wholeList.Add(d);
if (d is IFillable)
filledList.Add(d);
}
public void DrawList(Graphics g) {
if (wholeList.Count == 0)
{
Font f = new Font("Arial", 10);
g.DrawString("沒有任何要繪製的內容;列表為空白...",
f, Brushes.Gray, 50, 50);
}
else
{
foreach (DShape d in wholeList)
d.Draw(g);
}
}
public IFillable[] GetFilledList() {
return (IFillable[])filledList.ToArray(typeof(IFillable));
}
}
以下為等同類的 Visual Basic .NET 代碼:
Visual Basic
.NET Public Class DShapeList
Dim wholeList As New ArrayList()
Dim filledList As New ArrayList()
Public Sub Add(ByVal d As DShape)
wholeList.Add(d)
If TypeOf d Is IFillable Then filledList.Add(d)
End Sub
Public Sub DrawList(ByVal g As Graphics)
If wholeList.Count = 0 Then
Dim f As New Font("Arial", 10)
g.DrawString("沒有任何要繪製的內容;列表為空白...", _
f, Brushes.Gray, 50, 50)
Else
Dim d As DShape
For Each d In wholeList
d.Draw(g)
Next
End If
End Sub
Public Function GetFilledList() As IFillable()
Return filledList.ToArray(GetType(IFillable))
End Function
End Class