有没有办法写下面的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... }
请注意,这与可选参数不完全相同,因为默认值通过可选参数进行硬编码到调用者中(这就是为什么存在限制).