编译时常量 StringFormat

compile-time constant StringFormat

我有一个将文本转换为位图的方法:

private Bitmap ConvertTextToImage(string text, FontFamily fontFamily, float fontSize, FontStyle fontStyle,
    StringFormat stringFormat, float MaxWidth, float MaxHeight, Color backgroundColor, Color foregroundColor)
{
    // some code...
}

除了 textfontFamilyfontSize,我想让所有参数都可选。但是,我不知道如何创建编译时常量 StringFormat。我希望它默认像 new StringFormat()

在您的情况下,您可以让 null 成为默认值,然后检查 null 并将其替换为您 do 想要的值默认值。

用一个例子更容易演示:

private Bitmap ConvertTextToImage(string text, FontFamily fontFamily, float fontSize, FontStyle fontStyle,
    StringFormat stringFormat = null, float MaxWidth = 10, float MaxHeight = 10, Color backgroundColor = default, Color foregroundColor = default)
{
    if (stringFormat == null)
        stringFormat = new StringFormat(); // Or whatever default you want.
    // some code...
}

或者(在许多情况下更灵活)有一个采用所有参数的重载,然后提供带有缺失参数的额外重载,调用带有所有参数的版本,为缺失参数传递适当的值:

private Bitmap ConvertTextToImage(string text, FontFamily fontFamily, float fontSize, FontStyle fontStyle,
    float MaxWidth, float MaxHeight, Color backgroundColor, Color foregroundColor)
{
    return ConvertTextToImage(text, fontFamily, fontSize, fontStyle, new StringFormat(), MaxWidth, MaxHeight, backgroundColor, foregroundColor);
}

对于你的例子,我认为第二种方法会更简单,因为你有一些其他参数(Color 参数)除了使用 default 关键字外不能有默认值.

如果您想检查这些值,请在构造函数中执行以下操作:

if (backgroundColor == default)
    backgroundColor = Color.Beige; // Who doesn't love beige?

这仅在您不想传递 RGB 和透明度值全为零的颜色时才有效,因为这是 Color 的默认值。

您可以在方法内分配 nulldefault 并初始化 stringFormat

private Bitmap ConvertTextToImage(string text, FontFamily fontFamily, float fontSize, FontStyle fontStyle,
         StringFormat stringFormat = default, float MaxWidth = default, float MaxHeight = default, Color backgroundColor = default, Color foregroundColor = default)
{
   if (stringFormat == null)
      stringFormat = new StringFormat();

   // ...other code.
}