2016-11-25 36 views
0

我有一個設置對象,其中包含許多字體的報表。我應該在字體屬性的設置器中處理舊的字體嗎?

他們默認這樣

public Font TitleFont { get; set; } = new Font("Arial", 8, FontStyle.Bold); 

,但他們可以在許多地方被用於GDI +的報道渲染之前得到改變。這不是在winForms控件中。

字體實現IDisposable,所以我應該處理舊的字體在屬性設置?還是應該將字體名稱,大小和樣式存儲爲3個屬性,並且只在需要時才創建字體?

+0

[我應該在處理控制字體時處理舊字體嗎?](http://stackoverflow.com/questions/29103522/should-i-dispose-of-the-old-font-when-改變字體的控制) – Jens

+0

@Jens我不認爲它是重複的,至少不是那個。這不是一個winforms控件,我的對象負責字體 – dibs487

+0

如果它「對字體負責」,它應該「處理」它。如果它只是使用它(例如,如果你已經開發了一個助手類或例程),它不應該 –

回答

0

這裏的主要問題是如果班級是負責字體。 如果是,就應該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; 
相關問題