c# - 如何使用 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"
,或使其成为必需?
解决方案
您可以在方法中将默认值替换为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个方法;一个带分隔符,一个不带.
推荐阅读
- unix - /proc/schedstats 中的“时间戳”是什么?
- python-3.x - 在 PyPi 上发布新版本后,自定义警告类似于基于 CLICK 的 CLI 应用程序的 pip 升级警告
- flutter - 如何在收听 Stream 时执行 setState()
- css - Pure-React-Carousel Flex 框对齐
- python - python / pandas如何将列表转换为单个单元格并以excel或cvs格式存储
- bash - 我可以在不使用 cat 的情况下将 shell 函数作为管道有条件地“消失”吗?
- time-complexity - 哪个更好:O(nm) 或 O(n log n)?
- javascript - Angular TypeScript:无法将数组分配给新数组
- node.js - findById 通过其 ID 显示产品详细信息的问题
- mysql - 根据情感 SQL 计算提及次数