代码之家  ›  专栏  ›  技术社区  ›  Neil N HLGEM

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

  •  14
  • Neil N HLGEM  · 技术社区  · 15 年前

    我开始利用.NET4.0中的可选参数

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

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

    我想把Color.Transparent作为rgb参数的默认值。问题是,我不断得到这个编译错误:

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

    如果我只能对可选参数使用基元类型,这真的会扼杀我的计划。

    2 回复  |  直到 15 年前
        1
  •  25
  •   Matthew Whited    15 年前

    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 直到运行时才设置值(由类型初始值设定项)

        2
  •  3
  •   Dave Markle    15 年前

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

    public myObject(int foo, string bar) : this (foo, bar, Color.Transparent) {};
    
    public myObject(int foo, string bar, Color RGB) {
    ...
    }
    
        3
  •  1
  •   dynamichael    5 年前

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

        4
  •  0
  •   Shaveek23    5 年前

    试试这个:

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