使用System.Drawing.Color类型的可选参数

Nei*_*l N 16 c# .net-4.0 optional-parameters

我开始利用.Net 4.0中的可选参数

我遇到的问题是当我尝试声明System.Drawing.Color的可选参数时:

public myObject(int foo, string bar, Color rgb = Color.Transparent)
{
    // ....
}
Run Code Online (Sandbox Code Playgroud)

我希望Color.Transparent是rgb参数的默认值.问题是,我一直得到这个编译错误:

'rgb'的默认参数值必须是编译时常量

如果我只能将原始类型用于可选参数,那么它真的会杀死我的计划.

Mat*_*ted 24

可以使用Nullable值类型来帮助处理这种情况.

public class MyObject 
{
    public Color Rgb { get; private set; }

    public MyObject(int foo, string bar, Color? rgb = null) 
    { 
        this.Rgb = rgb ?? Color.Transparent;
        // .... 
    } 
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,这是必需的原因是因为在编译期间在调用点填充了默认值,并且static readonly直到运行时才设置值.(通过类型初始化程序)

  • @Neil N,类型名称"Color"之后的问号使得该结构成为一个"Nullable <Color>". (2认同)

dyn*_*ael 2

使用 'default' 关键字进行更新,自 C# 7.1 起可用:

public myObject(int foo, string bar, Color rgb = default) {
    // ....
}
Run Code Online (Sandbox Code Playgroud)

Color 结构体的默认值是一个空结构体,相当于 Color.Transparent