[英]Best way to create reusable objects like Fonts using C#
我有一個要在其中創建用戶控件的應用程序,為此,我定義了一個類來重用一些看起來像這樣的字體:
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
東西,但是為了簡單起見,我還可以改進此代碼嗎?
在創建許多對象之前,請分析是否確實需要它? 大多數控件都有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; }
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.