Are private Fonts and Brushes evil?
I have some classes which have Fonts and Brushes as private fields. Something says me this isn't correct practice, and should be avoided, yet I don't know why .... (Darn subconsiousness :-) )
Is this true, and why is it bad practice ?
class SomeControl: Panel
{
private Font titelFont = new Font("Arial", 8.25f, FontS开发者_高级运维tyle.Bold);
private SolidBrush whiteBrush = new SolidBrush(Color.White);
public SomeControl()
{
//Do stuff
}
}
I don't see why it's bad.
When using brushes, you already have static Brushes
class you may want to reuse instead of creating your own (just like you do with common colors).
For example, instead of creating whiteBrush
, you may rather use Brushes.White
directly.
Of course, it gives you only a common set of brushes, so you still need to create your own brush for any other color.
Just remember than fonts and brushes must be properly disposed. It means that when using your own fonts and brushes as a property or a field of a class, this class must implement IDisposable
and properly dispose those fonts and brushes.
Having them private looks fine to me.
But you should either make them static or override the Dispose
method in SomeControl
and dispose titelFont
and whiteBrush
there.
It is also hard to configure the fonts and brushes in the designer if you don't make them public properties.
The tricky thing is making sure that they get disposed...
But (to make it harder) only if they aren't the inbuilt system brushes etc - since they don't really belong to your form.
If they are diaposed in Dispose() then this is fine. Otherwise it can slowly leak handles. GC might catch them, but this is not deterministic.
if you want to change the font or the brushcolor from outside you have to make it to an public property, if not just let it private.
Don't forget to dispose the brush with the control. I personaly only set the color of the brush and create the brush itself in on paint.
private Color _WhiteBrush = Color.White;
public Color WhiteBrush
{
get
{
return _WhiteBrush;
}
set
{
_WhiteBrush = value;
this.Invalidate();
}
}
protected override void OnPaint(PaintEventArgs e)
{
using (SolidBrush sb = new SolidBrush(this.WhiteBrush))
{
e.Graphics.FillRectangle(sb, this.ClientRectangle);
}
}
精彩评论