使用C#创建可重用对象(如字体)的最佳方式

本文关键字:字体 方式 最佳 对象 创建 使用 | 更新日期: 2024-10-23 17:27:54

我有一个创建用户控件的应用程序,为此我定义了一个类来重用一些字体,如下所示:

public sealed class MyFonts
{       
    private static Font Tahoma7Regular = new Font("Tahoma", 7, FontStyle.Regular);
    private static Font Tahoma9Regular = new Font("Tahoma", 9, FontStyle.Regular);
    private static Font Tahoma9Bold = new Font("Tahoma", 9, FontStyle.Bold);       
    public static Font ChannelText = new Font("Tahoma", 12, FontStyle.Bold);       
    public static Font ClockText = Tahoma7Regular;
    public static Font HelpText = Tahoma9Regular;       
    public static Font RollFieldText = Tahoma9Bold;      
}

有什么方法可以改进它吗?我在反编译器工具中看到了Brushes类,他们使用了一种名为ThreadData的东西,我不知道,但为了简单起见,我也可以改进这个代码吗?

使用C#创建可重用对象(如字体)的最佳方式

在创建这么多对象之前,分析一下是否真的需要它?大多数控件都有一个Font属性(具有默认值)。您只需要在那里设置值,而不需要创建新对象。

ThreadData听起来像是线程之间共享数据的某种机制。

看看Brushes类:

public static Brush MediumAquamarine { get; }

也许可以稍微调整一下你的课程,使其更像上面的内容。在我看来,看起来更干净。

如果您正在构建用户控件,则不应该使用静态字段。用户控件的主要目标是可重用,因此您不希望对字体等属性使用固定值;这些属性将由usercontrol父级设置。

因此,您可能想要编写的是属性(使用Description等属性也很有用):

[Category("Appearance"), Description("Gets or sets the text channel font.")]
[Browsable(true)]
public Font ChannelFont { get; set; }
[Category("Appearance"), Description("Gets or sets the text clock font.")]
[Browsable(true)]
public Font ClockFont { get; set; }
...