传递空数组作为可选参数的默认值 [英] Passing an empty array as default value of an optional parameter
本文介绍了传递空数组作为可选参数的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何定义一个函数,它接受一个可选的阵列空数组作为默认?
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)
结果:
有关数组默认参数值必须是一个编译时间常数。
Default parameter value for 'array' must be a compile-time constant.
推荐答案
您不能创建对象引用的编译时间常数。
You can't create compile-time constants of object references.
唯一有效的编译时间常数可以使用空
,所以更改code这样:
The only valid compile-time constant you can use is null
, so change your code to this:
public void DoSomething(int index, ushort[] array = null,
bool thirdParam = true)
和你的方法内做到这一点:
And inside your method do this:
array = array ?? new ushort[0];
这篇关于传递空数组作为可选参数的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文