Advanced Optional Parameters (c#) [duplicate]

廉价感情. 提交于 2020-01-03 08:42:15

问题


The below code would be quite cool if it worked. However, I can't get it to compile, so I'm assuming this isn't going to work in any form?

public void foo(char[] bar = new char[]{'a'})
{
}

The next-best option is to just do

public void foo(char[] bar = null)
{
   if (bar==null)
      bar = new {'a'};
}

回答1:


No it's not possible. The default value needs to be a compile-time constant. The default value will be inserted into the caller, not the callee. Your code would be a problem if the caller has no access to the methods used to create your default value.

But you can use simple overloads:

public void foo(char[] bar)
{
}

public void foo()
{
  foo(new char[]{'a'});
}



回答2:


No, because optional parameter default values need to be constant.

Why do optional parameters in C# 4.0 require compile-time constants?




回答3:


That will never work because char[] is not a value type but rather a reference type. Only value types can have constants assigned to them in optional parameters. You cannot have a reference to an object (such as an array) at compile time. (Null is the only valid value for an optional reference type.)




回答4:


Other comments apply as well, but also consider that, since the default value is inserted into the caller at compile time, changing the default value at some later date will not change the value in the caller code (assuming it's being called from another assembly.) Because of this, what you propose as a work-around, or next-best option, is in fact a better practice.




回答5:


only with value types you have the possibility to set the default value of a parameter to compile-time constants (making it optional). For reference types, only strings have that ability. Other types can only be set to null.

edit: thanks @Martinho Fernandes for pointing that out. For value types, only compile-time constants are allowed



来源:https://stackoverflow.com/questions/5391593/advanced-optional-parameters-c

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