【问题标题】:Optional parameters “must be a compile-time constant” with a const still bugging可选参数“必须是编译时常量”,而 const 仍然存在问题
【发布时间】:2014-07-31 10:46:42
【问题描述】:

我都读过

Optional parameters "must be a compile-time constant"

Default parameter for value must be a compile time constant?

但这一直没有编译声明,将Empty标记为非常量。

public class MyClass
{
private const string Empty = string.Empty;

private string WriteFailedList(string prefix = Empty, DeployResponse Ret)
    {
        StringBuilder sb = new StringBuilder();
        var errorItems = Ret.Items.TakeWhile(item => item.Status == DeployItem.ItemStatus.Error);
        foreach (var item in errorItems)
            sb.AppendLine(string.Format("{0} {1}",prefix,item.Filename));
        return sb.ToString();
    }
}

@Edit:来自 Jon Skeet 的代码良好实践建议。

【问题讨论】:

标签: c# constants optional-parameters


【解决方案1】:

你给出的代码有两个问题:

  • 可选参数必须放在最后(params 参数除外)
  • const 字段必须分配编译时常量,而string.Empty 不是 const 字段
  • 因为Empty 不是有效的const,所以您的默认值不是const。这只是第二期的推论

这两个都很容易解决:

private const string Empty = ""; // Literal rather than String.Empty
...

// Parameter name changed to be more readable and conventional
private string WriteFailedList(DeployResponse response, string prefix = Empty)
{
    ...
}

或者去掉你自己的Empty常量:

private string WriteFailedList(DeployResponse response, string prefix = "")
{
    ...
}

(我还建议您对参数和局部变量使用camelCase - 所以errorItems 而不是ErrorItems。或者实际上只是errors。我也会使用foreach循环而不是调用ToList(),然后使用ForEach。)

【讨论】:

  • 我只是在想这个,当我按照你的建议更改顺序时,string.Empty 对我大喊它不是一个常数。似乎错误来自.net“未编译”代码建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-11
  • 1970-01-01
  • 1970-01-01
  • 2020-10-04
  • 2022-07-07
  • 1970-01-01
相关资源
最近更新 更多