How to set optional parameter without compile-time constant

泄露秘密 提交于 2019-12-30 07:57:13

问题


Is there a way to write the C# method below:

public string Download(Encoding contentEncoding = null) {
    defaultEncoding = contentEncoding ?? Encoding.UTF8;
    // codes...
}

with a default parameter added so it looks like this:

public string Download(Encoding contentEncoding = Encoding.UTF8) {
    // codes...
}

without using a compile-time constant?


回答1:


In short. No.

Optional parameters are required to be compile time constants or value types.

From Named and Optional Arguments (C# Programming Guide) on MSDN:

Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. A default value must be one of the following types of expressions:

  • a constant expression;
  • an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;
  • an expression of the form default(ValType), where ValType is a value type.

What you seem to want to achieve can be accomplished by overloading:

public string Download()
{
   return Download(Encoding.UTF8);
}

public string Download(Encoding contentEncoding)
{
   defaultEncoding = contentEncoding ?? Encoding.UTF8;
   // codes...
}

Note that this is not quite the same as optional parameters, as the default value gets hard coded into the caller with optional parameters (which is why the restrictions for them exist).




回答2:


Use overloads:

public string Download(Encoding contentEncoding)
{
   // codes...
}

public string Download()
{
    return Download(Encoding.UTF8);
}



回答3:


public static string Download(Encoding encoder = null)
{
    if (encoder == null)
        encoder = Encoding.Default


   string returnVal="";
   // do something

    return returnVal;
}


来源:https://stackoverflow.com/questions/14789439/how-to-set-optional-parameter-without-compile-time-constant

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