c# - 如何使用Environment.NewLine作为可选参数默认值

标签 c# optional-parameters compile-time-constant

只要有可能,我更喜欢 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/

相关文章:

c++ - C++11 之前的 "Constant expressions"

c++ - 如何定义作为不可实例化类的静态成员的数组的大小?

c# - 为什么客户端不能与WCF服务器直接对话(!),而不是使用这样做的代理类?

c# - 从 MVVM 的 subview 模型中引用方法和存储库

java - 有没有办法让 NULL 值作为 MySql 中的可选条件?

c++ - 在 constexpr 构造函数中初始化数组是否合法?

c# - 自定义对象序列化与 PreserveReferencesHandling

c# - .NET Core - 在 C# 代码中获取项目描述

带有可选参数的 Groovy 方法

具有互斥可选参数的 python 类/子类,使用父类(super class)的实例作为可能的构造函数