F#Option等效于C#操作员 [英] F# Option equivalent of C#'s ?? operator

查看:82
本文介绍了F#Option等效于C#操作员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种获取F#选项的值或使用默认值(如果它为None)的方法. 这似乎很常见,我无法相信预定义的内容不存在.这是我现在的操作方法:

I am looking for a way to get the value of an F# option or use a default value if it is None. This seems so common I can't believe something predefined doesn't exist. Here is how I do it right now:

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

我(某种程度上)正在寻找与C#等效的F#?运算符:

I am (sort of) looking for the F# equivalent of the C# ?? operator:

string test = GetString() ?? "This will be used if the result of GetString() is null.";

我认为这是一个非常基本的任务,但选项模块中没有任何功能.我想念什么?

No function in the Option module does what I think is a pretty basic task. What am I missing?

推荐答案

您在寻找 [MSDN] ('T option -> 'T -> 'T).

通常用于为可选参数提供默认值:

It's often used to provide a default value for optional arguments:

type T(?arg) =
  member val Arg = defaultArg arg 0

let t1 = T(1) 
let t2 = T() //t2.Arg is 0

这篇关于F#Option等效于C#操作员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆