C#中的可选数组参数

时间:2011-11-21 14:54:33

标签: c# c#-4.0

  

可能重复:
  passing an empty array as default value of optional parameter in c#

我的方法如下所示。目前参数tags不是可选的

void MyMethod(string[] tags=null)
{
   tags= tags ?? new string[0];
   /*More codes*/
}

我想根据tags将参数c#设置为可选参数,以使参数可选,您可以在方法签名中设置默认值。我试过下面的黑客但没有工作。

无效的代码 - 1

void MyMethod(string[] tags=new string[0]){}

无效的代码 - 2

void MyMethod(string[] tags={}){}

请告诉我我错过了什么。


我已经看过这个问题了

Passing an empty array as default value of an optional parameter

2 个答案:

答案 0 :(得分:43)

可选参数的documentation表示:

  

默认值必须是以下类型的表达式之一:

     
      
  • 一个常量表达式;

  •   
  • 表单new ValType(),其中ValType是值类型,例如enumstruct;

  •   
  • 表单default(ValType),其中ValType是值类型。

  •   

由于new string[0]既不是常量表达式,也不是new语句后跟值类型,因此不能将其用作默认参数值。

您问题中的第一个代码摘录确实是一个很好的解决方法:

void MyMethod(string[] tags = null)
{
   tags = tags ?? new string[0];
   // Now do something with 'tags'...
}

答案 1 :(得分:3)

不确定我是否正确行事。

  static void Main(string[] args)
        {
                TestMe();

        }


private static void TestMe(string[] param = null)
    {
        if (param == null)
        { 
            Console.WriteLine("its empty");
        }
    }

param的值也必须是编译时间常量