【发布时间】:2019-05-19 08:02:37
【问题描述】:
我更喜欢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",或使其成为必需?
【问题讨论】:
-
参数为
null时,能否将null作为默认值,在方法内部切换到Environment.NewLine? -
你总是可以用“老办法”来做:写2个方法;一个有分隔符,一个没有。
标签: c# optional-parameters compile-time-constant