【问题标题】:compile-time constant StringFormat编译时常量 StringFormat
【发布时间】:2020-08-26 08:37:03
【问题描述】:

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

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()

【问题讨论】:

  • 创建一个具有所需签名的新函数来调用该函数。

标签: c# optional-parameters compile-time-constant


【解决方案1】:

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

这更容易用一个例子来演示:

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 的默认值。

【讨论】:

  • 我发现backgroundColorforegroundColor 需要相同的解决方案。
  • 或者我可以使用KnownColor backgroundColor = KnownColor.Transparent 然后Color.FromKnownColor(backgroundColor)
【解决方案2】:

您可以分配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.
}

【讨论】:

  • 对于StringFormatdefault 是否等于null
  • @AmirSinaMashayekh 是的,default 的引用类型是 null,请参阅 here,但您当然可以简单地使用 null
猜你喜欢
  • 2011-11-25
  • 2011-12-26
  • 1970-01-01
  • 2012-02-23
  • 2014-09-03
  • 2012-06-13
  • 1970-01-01
相关资源
最近更新 更多