首页 > 解决方案 > 如何使用 Environment.NewLine 作为可选参数默认值

问题描述

我更喜欢Environment.NewLine尽可能"\r\n",即使这个项目是仅限 Windows 的。我想知道是否有办法将它用作可选参数的默认值。

考虑扩展方法

public static string ToSummaryString<T>(
    this IEnumerable<T> items, 
    string delimiter = Environment.NewLine)

和编译时错误

'delimiter' 的默认参数值必须是编译时常量

我也尝试过使用参数属性,命运相似

public static string ToSummaryString<T>(
    this IEnumerable<T> items, 
    [Optional, DefaultParameterValue(Environment.NewLine)] string delimiter)

属性参数必须是属性参数类型的常量表达式、typeof 表达式或数组创建表达式

那么有什么解决方法吗?还是我唯一的选择是将其硬编码为"\r\n",或使其成为必需?

标签: c#optional-parameterscompile-time-constant

解决方案


您可以在方法中将默认值替换为Null然后使用null-coalescing operator。像这样的东西:

public static string ToSummaryString<T>(this IEnumerable<T> items, string delimiter = null)
{
    var realDelimiter = delimiter ?? Environment.NewLine;
}

作为替代方案,您也可以使用Method-Overloading,正如@Dennis_E也提到的那样:编写2个方法;一个带分隔符,一个不带.


推荐阅读