C#中的FSharpChoice

Pra*_*eep 6 c# f#

我想FSharpChoice在C#项目中使用type.我创造了一个这样的选择

var a = FSharpChoice<T1,T2,T3>.NewChoice1Of3(instofT1);
Run Code Online (Sandbox Code Playgroud)

现在我如何instofT1摆脱选择类型.

我看到我可以做一个,IsChoice1Of3但我如何得到选择对象中的值?

Tom*_*cek 6

我可能不会直接使用C#中的类型 - 你可以这样做,但结果代码不会很好.我可能会声明我自己的Choice类型,如下所示:

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, ...)
Run Code Online (Sandbox Code Playgroud)

这使用在C#中byref作为out参数出现的参数,因此您可以编写:

int num;
string str;
if (choice.TryGetChoice1Of2(out num)) // ...
else if (choice.TryGetChoice2Of2(out str)) // ...
else // assert(false)
Run Code Online (Sandbox Code Playgroud)

这绝对是使用C#类型的更愉快的方式(并且它使用熟悉的模式,例如,使用Int32.TryParse).

  • 我喜欢这种方法,但我更喜欢朱丽叶在其他答案中的方法:http://stackoverflow.com/questions/3151702/discriminated-union-in-c/3199453#3199453. (3认同)

kvb*_*kvb 5

将值转换为FSharpChoice<T1,T2,T3>.Choice1Of3并使用该Item属性.

联盟类型从其他CLI语言使用的编译形式在F#规范有关如何判别工会代表的更多信息.