在F#API中,是否有类似Option.ofNull的内容?
我从F#使用的许多API都允许空值。我喜欢把它们变成选择。有没有一种简单的内置方法可以做到这一点?以下是我这样做的一种方式:在F#API中,是否有类似Option.ofNull的内容?,f#,F#,我从F#使用的许多API都允许空值。我喜欢把它们变成选择。有没有一种简单的内置方法可以做到这一点?以下是我这样做的一种方式: type Option<'A> with static member ofNull (t:'T when 'T : equality) = if t = null then None else Some t 有没有内置的东西已经做到了这一点 根据丹尼尔的回答,不需要平等空约束 type Option<'A> with
type Option<'A> with
static member ofNull (t:'T when 'T : equality) =
if t = null then None else Some t
有没有内置的东西已经做到了这一点
根据丹尼尔的回答,不需要平等<可以改用代码>空
约束
type Option<'A> with
static member ofNull (t:'T when 'T : null) =
if t = null then None else Some t
type选项没有内置的功能。顺便说一句,您可以不使用相等约束:
//'a -> 'a option when 'a : null
let ofNull = function
| null -> None
| x -> Some x
或者,如果要处理从其他语言传递的F值,并且未选中。defaultof
:
我将其称为选项。ofObj
我建议我们为此在F#API中添加一个公共函数。在这里投票:干得好-我自己现在的票数很紧:(我要指出的是,任何读者——从F#4开始,它现在被内置到FSharp.Core中。正如您所说,对于这个函数,最好不要对type参数使用null
约束,但我不确定装箱是否是移除类型约束的最佳方式——为什么这个函数接受值类型有意义呢实现这一点的另一种方法是手动指定类型参数上的not struct
约束,然后使用System.Object.ReferenceEquals(null,x)
检查null。@JackP:这些都是合理的改进。当然,您可以仅使用类型注释来避免box
:let Of null(x:obj)=…
//'a -> 'a option when 'a : null
let ofNull = function
| null -> None
| x -> Some x
//'a -> 'a option
let ofNull x =
match box x with
| null -> None
| _ -> Some x