有没有办法写下面的C#方法:
public string Download(Encoding contentEncoding = null) { defaultEncoding = contentEncoding ?? Encoding.UTF8; // codes... }
public string Download(Encoding contentEncoding = Encoding.UTF8) { // codes... }
不使用编译时常数?
解决方法
简而言之.没有.
需要可选参数来编译时间常数或值类型.
从Named and Optional Arguments (C# Programming Guide)在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()
,whereValType
is a value type,such as an enum or a struct;- an expression of the form
default(ValType)
,whereValType
is a value type.
你似乎想要实现的是可以通过重载来实现的:
public string Download() { return Download(Encoding.UTF8); } public string Download(Encoding contentEncoding) { defaultEncoding = contentEncoding ?? Encoding.UTF8; // codes... }