如何在没有编译时常量的情况下设置可选参数 [英] How to set optional parameter without compile-time constant

查看:29
本文介绍了如何在没有编译时常量的情况下设置可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法写下面的C#方法:

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...
}

不使用编译时常量?

推荐答案

简而言之.号

可选参数必须是编译时常量或值类型.

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

来自 MSDN 上的命名和可选参数(C# 编程指南):

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:

  • 一个常量表达式;
  • 形式为 new ValType() 的表达式,其中 ValType 是值类型,例如枚举或结构体;
  • default(ValType) 形式的表达式,其中 ValType 是值类型.
  • 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).

这篇关于如何在没有编译时常量的情况下设置可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆