可选参数“必须是编译时常量”,const仍然存在错误

时间:2014-06-10 15:27:53

标签: c# const optional-parameters

我已经阅读了两个

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采取的代码良好实践建议。

1 个答案:

答案 0 :(得分: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,实际上。{I>我还使用foreach循环而不是调用ToList(),然后使用ForEach。)

相关问题