可能重复:
将空数组作为c#中可选参数的默认值传递
我有一个看起来像下面的方法.目前参数tags不是可选的
void MyMethod(string[] tags=null)
{
tags= tags ?? new string[0];
/*More codes*/
}
Run Code Online (Sandbox Code Playgroud)
我希望将参数设置tags为可选,c#以使参数可选,您可以在方法签名中设置默认值.我试过下面的黑客但没有工作.
代码没有用 - 1
void MyMethod(string[] tags=new string[0]){}
Run Code Online (Sandbox Code Playgroud)
代码没有用 - 2
void MyMethod(string[] tags={}){}
Run Code Online (Sandbox Code Playgroud)
请告诉我我错过了什么.
我已经看过这个问题
Fré*_*idi 44
可选参数的文档说:
默认值必须是以下类型的表达式之一:
一个恒定的表达;
表单的表达式
new ValType(),其中ValType是值类型,例如aenum或astruct;表单的表达式
default(ValType),其中ValType是值类型.
既然new string[0]既不是常量表达式也不是new值后跟值类型的语句,它不能用作默认参数值.
您问题中的第一个代码摘录确实是一个很好的解决方法:
void MyMethod(string[] tags = null)
{
tags = tags ?? new string[0];
// Now do something with 'tags'...
}
Run Code Online (Sandbox Code Playgroud)
不知道我是否做对了这行得通。
static void Main(string[] args)
{
TestMe();
}
private static void TestMe(string[] param = null)
{
if (param == null)
{
Console.WriteLine("its empty");
}
}
Run Code Online (Sandbox Code Playgroud)
param 的值也必须是编译时常量
| 归档时间: |
|
| 查看次数: |
22222 次 |
| 最近记录: |