加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何设置可选参数,无需编译时常数

发布时间:2020-12-15 04:09:15 所属栏目:百科 来源:网络整理
导读:有没有办法写下面的C#方法: public string Download(Encoding contentEncoding = null) { defaultEncoding = contentEncoding ?? Encoding.UTF8; // codes...} 添加了默认参数,如下所示: public string Download(Encoding contentEncoding = Encoding.UTF8
有没有办法写下面的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(),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.

你似乎想要实现的是可以通过重载来实现的:

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

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

请注意,这与可选参数不完全相同,因为默认值通过可选参数进行硬编码到调用者中(这就是为什么存在限制).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读