有没有办法写下面的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... }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。