【问题标题】:calling a method with multiple default values调用具有多个默认值的方法
【发布时间】:2014-02-19 15:26:45
【问题描述】:

我想知道,因为我有一个带有多个默认参数的方法

private string reqLabel(string label, byte fontSize = 10, string fontColour = "#000000", string fontFamily = "Verdana"  )
{
   return "<br /><strong><span style=\"font-family: " + fontFamily + ",sans-serif; font-size:" +fontSize.ToString() + "px; color:"+ fontColour + "; \">" + label +" : </span></strong>";
}

当我调用该方法时,我必须按顺序进行

reqLabel("prerequitie(s)")
reqLabel("prerequitie(s)", 12) 
reqLabel("prerequitie(s)", 12 , "blue")
reqLabel("prerequitie(s)", 12 , "blue", "Tahoma")

所以我的问题是,有没有办法跳过前几个默认参数?

假设我只想输入颜色和字体系列,如下所示:

reqLabel("Prerequisite(s)" , "blue" , "Tahoma") 

/* or the same with 2 comma's where the size param is supposed to be. */

reqLabel("Prerequisite(s)" ,  , "blue" , "Tahoma") 

【问题讨论】:

    标签: c# methods


    【解决方案1】:

    是的,可以通过显式命名:

    reqLabel("Prerequisite(s)" , fontColour: "blue", fontFamily: "Tahoma")
    

    请注意,命名参数应始终位于最后一个参数 - 您不能在命名后指定定位参数。换句话说,这是不允许的:

    reqLabel("Prerequisite(s)" , fontColour: "blue", "Tahoma")
    

    【讨论】:

    • @Alberto,Adam,感谢您指出语法问题。总是倾向于混淆 this 和匿名对象的语法,可能是因为我更经常使用后一种方式。
    【解决方案2】:

    使用named arguments

    reqLabel("prerequitie(s)", fontSize: 11)
    

    【讨论】:

      【解决方案3】:

      你需要使用名称参数调用:

      reqLabel("Prerequisite(s)" , fontColour: "blue" , fontFamily: "Tahoma") 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-16
        • 2019-10-10
        • 2019-04-24
        • 2020-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-27
        相关资源
        最近更新 更多