FSharpChoice in C#

后端 未结 3 660
别跟我提以往
别跟我提以往 2021-01-05 14:58

I am trying to use FSharpChoice type in a C# project. I have created a choice like so

var a = FSharpChoice.NewChoice1Of3(instofT         


        
3条回答
  •  没有蜡笔的小新
    2021-01-05 15:17

    I probably wouldn't use the type directly from C# - you can do that, but the resulting code won't be very nice. I'd probably declare my own Choice type that would look like this:

    type Choice<'T1, 'T2> private (opt1, opt2) =
      member x.TryGetChoice1Of2(arg:byref<'T1>) = //'
        match opt1 with
        | Some v -> arg <- v; true
        | _ -> false
      // Similar code for 'TryGetChoice2Of2'
    
    type Choice = // static methods for creating (Choice1Of2, ...)
    

    This uses byref parameters which appear as out parameters in C#, so you could write:

    int num;
    string str;
    if (choice.TryGetChoice1Of2(out num)) // ...
    else if (choice.TryGetChoice2Of2(out str)) // ...
    else // assert(false)
    

    This is definitely more pleasant way of working with the type from C# (and it uses pattern familiar from, for example, working with Int32.TryParse).

提交回复
热议问题