传递一个空数组作为可选参数的默认值
如何定义一个函数,该函数接受一个可选数组,默认数组为空数组?
public void DoSomething(int index, ushort[] array = new ushort[] {},
bool thirdParam = true)
结果:
“array”的默认参数值必须是编译时常量。
How does one define a function that takes an optional array with an empty array as default?
public void DoSomething(int index, ushort[] array = new ushort[] {},
bool thirdParam = true)
results in:
Default parameter value for 'array' must be a compile-time constant.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法创建对象引用的编译时常量。
您可以使用的唯一有效的编译时常量是
null
,因此将您的代码更改为:在您的方法中执行以下操作:
(来自注释) 从 C# 8 开始,您还可以使用更短的语法:
You can't create compile-time constants of object references.
The only valid compile-time constant you can use is
null
, so change your code to this:And inside your method do this:
(from comments) From C# 8 onwards you can also use the shorter syntax:
如果您可以将数组作为最后一个参数,您也可以这样做:
如果未指定,编译器将自动传递一个空数组,并且您可以更加灵活地将数组作为单个参数传递或将元素直接作为方法的可变长度参数。
If you can make the array the last argument you could also do this:
The compiler will automatically pass an empty array if it is not specified, and you get the added flexibility to either pass an array as a single argument or put the elements directly as variable length arguments to your method.
我知道这是一个老问题,虽然这个答案并不能直接解决如何绕过编译器施加的限制,但方法重载是一种替代方法:
I know it's an old question, and whilst this answer doesn't directly solve how to get around the limitations imposed by the compiler, method overloading is an alternative: