我如何实现函数的“可选”参数,以便在未给出 endMarker
时,我将使用必需参数 startMarker
中的值?我目前使用可空类型并检查 endMarker
是否为 null 我将其设置为 startMarker
protected void wrapText(string startMarker, string? endMarker = null) {
if (endMarker == null)
endMarker = startMarker;
}
但现在的问题是我收到一条错误消息,提示它无法将 string?
转换为 string
(string)endMarker
如何将 endMarker
转换为 string
以便我可以使用它?还是有更好的实现方式?
最佳答案
这会起作用:
protected void wrapText(string startMarker, string endMarker = null) {
if (endMarker == null)
endMarker = startMarker;
}
换句话说:从 string?
中删除问号. System.String
是引用类型,已经可以是null
. Nullable<T>
结构只能用于值类型。
关于C#:有一个 "Optional"参数,默认情况下使用所需参数的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3582092/