可能的重复:
在 C# 中传递一个空数组作为可选参数的默认值 https://stackoverflow.com/questions/3480382/passing-an-empty-array-as-default-value-of-optional-parameter-in-c-sharp
我有一个如下所示的方法。目前,参数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={}){}
请提出我所缺少的内容。
我已经看到这个问题了:
传递一个空数组作为可选参数的默认值 https://stackoverflow.com/questions/3480382/passing-an-empty-array-as-default-value-of-optional-parameter-in-c-sharp
The 文档 http://msdn.microsoft.com/en-us/library/dd264739.aspx对于可选参数说:
默认值必须是以下类型的表达式之一:
常量表达式;
形式的表达new ValType()
, where ValType
是一个值类型,例如enum
or a struct
;
形式的表达default(ValType)
, where ValType
是一个值类型。
Since new string[0]
既不是常量表达式也不是new
语句后跟一个值类型,它不能用作默认参数值。
您问题中的第一个代码摘录确实是一个很好的解决方法:
void MyMethod(string[] tags = null)
{
tags = tags ?? new string[0];
// Now do something with 'tags'...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)