F# 选项相当于 C# 的 ??运算符(operator)

标签 f# option

我正在寻找一种方法来获取 F# 选项的值,或者如果它是 None 则使用默认值。
这似乎很常见,我不敢相信预定义的东西不存在。这是我现在的做法:

// val getOptionValue : Lazy<'a> -> Option<'a> -> 'a    
let getOptionValue (defaultValue : Lazy<_>) = function Some value -> value | None -> defaultValue.Force ()

我(有点)在寻找相当于 C# 的 F# ?运算符(operator):
string test = GetString() ?? "This will be used if the result of GetString() is null.";

Option 模块中没有任何功能可以完成我认为非常基本的任务。我错过了什么?

最佳答案

您可以轻松创建自己的运算符(operator)来做同样的事情。

let (|?) = defaultArg

您的 C# 示例将变为
let getString() = (None:string option) 
let test = getString() |? "This will be used if the result of getString() is None.";;

val getString : unit -> string option 
val test : string = "This will be used if the result of getString() is None."

Here's a blog post更详细一点。

编辑:尼康三世为运算符(operator)提供了更好的实现,所以我更新了它。

关于F# 选项相当于 C# 的 ??运算符(operator),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12642554/

相关文章:

javascript - 在基于当前选项的选择中添加选项

scala - 在 Scala 中将选项转换为任一

java - 这个叫什么? (就像二进制文件一样,我认为呢?)

f# - 构建代码表达式 "Manually"

c# - F#:需要帮助将 C# 转换为 F#

.net - 将 Foq 与 F# 函数类型一起使用

scala - 在 Scala 中处理可选的 xml 属性

unicode - 从 unicode 字符串中获取随机表情符号/字符

f# 模式匹配相反的值

ruby-on-rails - 如何选择f.select rails