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

标签 c# nullable

我如何实现函数的“可选”参数,以便在未给出 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/

相关文章:

c# - Interlocked.Exchange 可空十进制

c# - Console.ReadLine() 跳过第一个输入字符

c# - 是否可以在 C# 中调用泛型参数的方法?

c# - 如何在 C# 中创建可被发现的 UPnP 服务

c# - 可空枚举的延迟属性

java - 是否有用于检查@Nonnull 和@Nullable 注释的良好Eclipse 插件?

string - 在 kotlin 中,空对象的 toString() 方法返回空字符串而不是 "null"的最佳方法是什么

c# - 写入 MySQL

c# - 如何对该异步代码进行单元测试?

php - MySQL 中非空列中的空字符串?