Here is an example function:
public void DrawSquare(int x, int y, Color boxColor = Color.Black)
{
//Code to draw the square goes here
}
The compiler keeps giving me the error: Default parameter value for 'boxColor'must be a compile-time constant
I have tried
Color.Black,
Color.FromKnownColor(KnownColor.Black), and
Color.FromArgb(0, 0, 0)
How do I make Color.Black be the default color? Also, I do not want to use a string Black
to specif开发者_高级运维y it (which I know would work). I want the Color.Black
value.
Do this:
void foo(... Color boxColor = default(Color))
{
if(object.Equals(boxColor, default(Color))) boxColor = Color.Black;
// ...
}
Quick aside: I like to use object.Equals
static method because it's a consistent way to write an equality comparison. With reference types such as string
, str.Equals("abc")
can throw NRE, whereas string.Equals(str, "abc"[,StringComparison.___])
will not. Color
is a value type and therefore will never be null, but it's better to be consistent in code style, especially at zero additional cost. Obviously this doesn't apply to primitives such as int
and even DateTime
, where ==
clearly states/communicates the mathematical equality comparison.
Or, with nullables (credit to Brian Ball's answer):
void foo(... Color? boxColor = null)
{
if(boxColor == null) boxColor = Color.Black;
// ...
}
Color.Black
is a static, not a constant, so no, you cannot do this.
To use a default, you can make the parameter nullable (Color?
), and if it is null, then set it to Black.
What's wrong with keeping it simple?
public void DrawSquare(int x, int y)
{
DrawSquare(x,y,Color.Black);
}
public void DrawSquare(int x, int y, Color color)
{
// Do your thing.
}
精彩评论