如何为函数实现"可选"参数,以便在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)
我怎么可以投endMarker给string这样我就可以使用它?还是有更好的方法来实现这个?
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.