与 C# 库交互时,我发现自己想要 C# 的空合并运算符来Nullable
结构和引用类型。
是否可以在 F# 中使用单个重载运算符来近似于此值,该运算符内联适当的if
情况?
是的,使用在此 SO 答案"F# 中的重载运算符"中找到的一些小黑客行为。
在编译时,可以内联单个运算符的 ('a Nullable, 'a) ->'a
或 ('a when 'a:null, 'a) -> 'a
用法的正确重载。甚至可以加入('a option, 'a) -> 'a
以获得更大的灵活性。
为了提供更接近 c# 运算符的行为,我设置了默认参数'a Lazy
,以便除非原始值null
,否则不会调用它的 source。
例:
let value = Something.PossiblyNullReturned()
|?? lazy new SameType()
实现:
NullCoalesce.fs [Gist]:
//https://gist.github.com/jbtule/8477768#file-nullcoalesce-fs
type NullCoalesce =
static member Coalesce(a: 'a option, b: 'a Lazy) =
match a with
| Some a -> a
| _ -> b.Value
static member Coalesce(a: 'a Nullable, b: 'a Lazy) =
if a.HasValue then a.Value
else b.Value
static member Coalesce(a: 'a when 'a:null, b: 'a Lazy) =
match a with
| null -> b.Value
| _ -> a
let inline nullCoalesceHelper< ^t, ^a, ^b, ^c when (^t or ^a) : (static member Coalesce : ^a * ^b -> ^c)> a b =
// calling the statically inferred member
((^t or ^a) : (static member Coalesce : ^a * ^b -> ^c) (a, b))
let inline (|??) a b = nullCoalesceHelper<NullCoalesce, _, _, _> a b
或者,我制作了一个库,它利用这种技术以及计算表达式来处理 Null/Option/Nullable,称为 FSharp.Interop.NullOptable
它改用运算符|?->
。
jbtule接受的答案以支持DBNull:
//https://gist.github.com/tallpeak/7b8beacc8c273acecb5e
open System
let inline isNull value = obj.ReferenceEquals(value, null)
let inline isDBNull value = obj.ReferenceEquals(value, DBNull.Value)
type NullCoalesce =
static member Coalesce(a: 'a option, b: 'a Lazy) = match a with Some a -> a | _ -> b.Value
static member Coalesce(a: 'a Nullable, b: 'a Lazy) = if a.HasValue then a.Value else b.Value
//static member Coalesce(a: 'a when 'a:null, b: 'a Lazy) = match a with null -> b.Value | _ -> a // overridden, so removed
static member Coalesce(a: DBNull, b: 'b Lazy) = b.Value //added to support DBNull
// The following line overrides the definition for "'a when 'a:null"
static member Coalesce(a: obj, b: 'b Lazy) = if isDBNull a || isNull a then b.Value else a // support box DBNull
let inline nullCoalesceHelper< ^t, ^a, ^b, ^c when (^t or ^a) : (static member Coalesce : ^a * ^b -> ^c)> a b =
((^t or ^a) : (static member Coalesce : ^a * ^b -> ^c) (a, b))
用法:
let inline (|??) a b = nullCoalesceHelper<NullCoalesce, _, _, _> a b
let o = box null
let x = o |?? lazy (box 2)
let y = (DBNull.Value) |?? lazy (box 3)
let z = box (DBNull.Value) |?? lazy (box 4)
let a = None |?? lazy (box 5)
let b = box None |?? lazy (box 6)
let c = (Nullable<int>() ) |?? lazy (7)
let d = box (Nullable<int>() ) |?? lazy (box 8)
我通常为此目的使用defaultArg
,因为它内置于语言中。