17

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

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

public myObject(int foo, string bar, Color rgb = Color.Transparent)
{
    // ....
}

我希望 Color.Transparent 成为 rgb 参数的默认值。问题是,我不断收到此编译错误:

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

如果我只能将原始类型用于可选参数,那真的会破坏我的计划。

4

4 回答 4

25

可空值类型可用于在这种情况下提供帮助。

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

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

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

于 2010-08-06T03:32:50.863 回答
3

对于这种情况,我根本不喜欢可选参数。IMO 可选参数的最佳用例是与 COM 互操作,其中使用了相当多的可选参数。像这样的情况是(我猜)可选参数直到 4.0 才进入语言的原因之一。

不要创建可选参数,而是像这样重载函数:

public myObject(int foo, string bar) : this (foo, bar, Color.Transparent) {};

public myObject(int foo, string bar, Color RGB) {
...
}
于 2010-08-06T02:48:37.537 回答
1

使用从 C# 7.1 开始可用的“默认”关键字进行了更新:

public myObject(int foo, string bar, Color rgb = default) {
    // ....
}

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

于 2020-10-25T03:48:52.730 回答
0

试试这个:

public myObject(int foo, string bar, string colorName = "Transparent")
{
    using (Pen pen = new Pen(Color.FromName(colorName))) //right here you need your color
    {
       ///enter code here
    }

}
于 2020-10-12T23:35:17.633 回答