C#:有一个"可选"参数,默认情况下使用所需参数的值

Jie*_*eng 4 c# nullable

如何为函数实现"可选"参数,以便在endMarker未给出时,我将使用所需参数中的值startMarker?我目前使用可空类型并检查是否endMarker为null我将其设置为startMarker

protected void wrapText(string startMarker, string? endMarker = null) { 
    if (endMarker == null)
        endMarker = startMarker; 
}
Run Code Online (Sandbox Code Playgroud)

但现在的问题是我得到一个错误,说它无法string?投入string

(string)endMarker
Run Code Online (Sandbox Code Playgroud)

我怎么可以投endMarkerstring这样我就可以使用它?还是有更好的方法来实现这个?

Ste*_*ven 17

This will work:

protected void wrapText(string startMarker, string endMarker = null) { 
    if (endMarker == null)
        endMarker = startMarker; 
}
Run Code Online (Sandbox Code Playgroud)

In other words: remove the question mark from the string?. System.String is a reference type and can already be null. The Nullable<T> structure can only be used on value types.

  • 只想添加,代码可以缩短为`endMarker = endMarker ?? startMarker` (12认同)
  • 值得注意的是,这只能在C#4及以后版本中实现. (5认同)
  • @JiewMeng 从 C# 8.0 开始,可以进一步缩短为 `endMarker ??= startMarker` (3认同)