Passing an empty array as default value of an optional parameter [duplicate]

[亡魂溺海] 提交于 2019-12-27 11:47:12

问题


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.


回答1:


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:

public void DoSomething(int index, ushort[] array = null,
  bool thirdParam = true)

And inside your method do this:

array = array ?? new ushort[0];



回答2:


If you can make the array the last argument you could also do this:

public void DoSomething(int index, bool wasThirdParam = true, params ushort[] array)

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.




回答3:


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:

   public void DoSomething(int index, bool thirdParam = true){
        DoSomething(index, new ushort[] {}, thirdParam);
   }

   public void DoSomething(int index, ushort[] array, bool thirdParam = true){

      ...
   }


来源:https://stackoverflow.com/questions/3480382/passing-an-empty-array-as-default-value-of-an-optional-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!