C#中的可选数组参数

可能重复:
传递一个空数组作为c#中可选参数的默认值

我有一个看起来像下面的方法。 目前,参数tags不是可选的

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

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

代码没有用 – 1

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

代码没有用 – 2

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

请告诉我我错过了什么。


我已经看过这个问题

将空数组作为可选参数的默认值传递

可选参数的文档说:

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

  • 不断表达;

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

  • forms为default(ValType)的表达式,其中ValType是值类型。

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

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

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

我不知道我是否正确行事。

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

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