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

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

问题描述

是否可以编写以下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#编程指南) :

每个可选参数在其定义中都有一个默认值.如果没有为该参数发送参数,则使用默认值.默认值必须是以下类型的表达式之一:

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天全站免登陆