我可以指定在C#4.0中的默认颜色参数? [英] Can I specify a default Color parameter in C# 4.0?

查看:277
本文介绍了我可以指定在C#4.0中的默认颜色参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个例子功能:

public void DrawSquare(int x, int y, Color boxColor = Color.Black)
{
    //Code to draw the square goes here 
}

编译器不断给我的错误:则是'boxColor'must是一个编译时间常数

The compiler keeps giving me the error: Default parameter value for 'boxColor'must be a compile-time constant

我曾尝试

Color.Black, 
Color.FromKnownColor(KnownColor.Black), and 
Color.FromArgb(0, 0, 0)

我如何Color.Black是默认颜色?另外,我不想使用字符串来指定它(我知道会的工作)。我想在 Color.Black 值。

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.

推荐答案

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.

这篇关于我可以指定在C#4.0中的默认颜色参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆