30

NullableC# ライブラリを操作していると、構造体と参照型の両方に C# の null 合体演算子が必要になります。

if適切なケースをインライン化する単一のオーバーロードされた演算子を使用して、F# でこれを近似することは可能ですか?

4

3 に答える 3

30

はい、このSOの回答「F#のオーバーロード演算子」にあるマイナーなハッカーを使用してください。

コンパイル時に、いずれかの使用法または単一の演算子の正しいオーバーロードを('a Nullable, 'a) ->'aインライン('a when 'a:null, 'a) -> 'a化できます。より柔軟にするために投げ込むことも('a option, 'a) -> 'aできます。

'a LazyC# 演算子に近い動作を提供するために、元の値が でない限りソースが呼び出されないように、既定のパラメーターを作成しましたnull

例:

let value = Something.PossiblyNullReturned()
            |?? lazy new SameType()

実装:

NullCoalesce.fs [要点]:

//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

別の方法として、 FSharp.Interop.NullOptAbleという Null/Option/Nullables を処理するための計算式と同様に、この手法を利用するライブラリを作成しました。

|?->代わりに演算子を使用します。

于 2014-01-17T19:46:55.743 に答える