C# 4.0:我可以使用 Color 作为具有默认值的可选参数吗?
public void log(String msg, Color c = Color.black)
{
loggerText.ForeColor = c;
loggerText.AppendText("\n" + msg);
}
这会导致错误:c 必须是编译时常量。我已经阅读了一些这方面的内容,大多数例子都是处理字符串和整数。我发现我可以使用 colorconverter 类,但我不确定它是否会非常有效。有没有办法只传递基本颜色作为可选参数?
public void log(String msg, String c = "Black")
{
ColorConverter conv = new ColorConverter();
Color color = (Color)conv.ConvertFromString(c);
loggerText.ForeColor = color;
loggerText.AppendText("\n" + msg);
}
public void log(String msg, Color c = Color.black)
{
loggerText.ForeColor = c;
loggerText.AppendText("\n" + msg);
}
This results in an error that c must be a compile-time constant. I've read up on this a little and most examples are dealing with strings and ints. I've figured out I can use the colorconverter class but I'm not sure it will be very efficient. Is there a way to just pass a basic color as an optional parameter?
public void log(String msg, String c = "Black")
{
ColorConverter conv = new ColorConverter();
Color color = (Color)conv.ConvertFromString(c);
loggerText.ForeColor = color;
loggerText.AppendText("\n" + msg);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我也遇到过这个问题,我发现的唯一解决方法是使用可空值。
其他可能的语法是:
I've run into this as well and the only workaround I've found is to use nullables.
Other possible syntax is:
您可以检查 Color 是否为 Color.Empty(这是默认值:
default(Color)
)或使用可为 null 的值并检查是否为 null。You could check if Color is Color.Empty (which is the default value:
default(Color)
) or use a nullable value and check for null.不要指定颜色。相反,提供“错误级别”,并在每个错误级别和颜色值之间建立映射。这样,0 及以下可能是黑色,然后 1 = 琥珀色,>2 = 红色。无需担心默认值和/或未指定值。
Don't specify the colour. Supply an "error level" instead, and have a mapping between each error level and a colour value. That way 0 and below could be black, then 1 = amber, >2 = red. No need to worry about default values and/or not specifying a value.
使用建议:
Usage suggestion: