只要有可能,我更喜欢 Environment.NewLine
而不是 "\r\n"
,即使这个项目仅适用于 Windows。我想知道是否有办法将其用作可选参数的默认值。
考虑扩展方法
public static string ToSummaryString<T>(
this IEnumerable<T> items,
string delimiter = Environment.NewLine)
和编译时错误
Default parameter value for 'delimiter' must be a compile-time constant
我也尝试过使用参数属性,结果类似
public static string ToSummaryString<T>(
this IEnumerable<T> items,
[Optional, DefaultParameterValue(Environment.NewLine)] string delimiter)
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
那么有什么解决办法吗?或者我唯一的选择是将其硬编码为 "\r\n"
,或将其设为必需?
最佳答案
您可以将默认值替换为 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个方法;一种带分隔符,一种不带分隔符。
关于c# - 如何使用Environment.NewLine作为可选参数默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53840892/