Can I specify a default Color parameter in C# 4.0?

偶尔善良 提交于 2019-12-20 17:32:38

问题


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 specify it (which I know would work). I want the Color.Black value.


回答1:


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.




回答2:


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;

  // ...
}



回答3:


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.
}


来源:https://stackoverflow.com/questions/4454336/can-i-specify-a-default-color-parameter-in-c-sharp-4-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!