這裏的主要問題是如果班級是負責字體。 如果是,就應該Dispose
字體:
public class MyFontStorage: IDisposable {
private Font m_MyFont;
...
public Font MyFont {
get {
return m_MyFont;
}
set {
if (m_MyFont == value)
return;
if (m_MyFont != null)
m_MyFont.Dispose();
m_MyFont = value;
}
}
protected virtual void Dispose(bool disposing) {
if (disposing) {
MyFont = null;
}
}
public void Dispose() {
Dispose(this);
GC.SuppressFinalize(this);
}
}
....
using (MyFontStorage storage = new MyFontStorage()) {
...
// Storage is responsible for the font
storage.MyFont = new Font(...);
...
// Control has responsibility for the font as well, that's why
// we have to create a copy in order to each font instance has one owner
MyControl.Font = new Font(MyFontStorage.MyFont, MyFontStorage.Font.Style);
...
}
創建副本而不只是分配是不好的做法(容易出錯),這就是爲什麼你可能要實施工廠 -
「我應該存儲的字體名稱,大小和樣式」
public class MyFontFactory {
private string m_FamilyName;
private float m_Size;
private FontStyle m_Style;
...
public MyFontFactory(Font propotype) {
...
m_FamilyName = propotype.FontFamily.Name;
m_Size = propotype.Size;
m_Style = propotype.Style;
}
public Font CreateFont() {
return new Font(m_FamilyName, m_Size, m_Style);
}
}
....
MyFontFactory factory = new factory(SomeControl.Font);
...
// Much more natural:
// MyFontFactory creates a new font and MyControl takes responsibility for it
MyControl.Font = factory.CreateFont();
最後,在輔助類/工具/程序等的情況下
public class MyFontMisc {
private Font m_MyFont;
public Font MyFont {
get {
return m_MyFont;
}
set {
m_MyFont = value;
}
}
// Just some computations
public float EmSizeInMillimeters {
get {
if (null == m_MyFont)
return 0.0;
...
}
}
}
......
// MyFontMisc doesn't hold any responsibility for the font
MyFontMisc misc = new MyFontMisc(SomeControl.Font);
// MyFontMisc just uses font for some computation and doesn't take
// any responsibility for the font (which owns to SomeControl)
Length = misc.EmSizeInMillimeters * 3.0f + 15.0f;
[我應該在處理控制字體時處理舊字體嗎?](http://stackoverflow.com/questions/29103522/should-i-dispose-of-the-old-font-when-改變字體的控制) – Jens
@Jens我不認爲它是重複的,至少不是那個。這不是一個winforms控件,我的對象負責字體 – dibs487
如果它「對字體負責」,它應該「處理」它。如果它只是使用它(例如,如果你已經開發了一個助手類或例程),它不應該 –