我想FSharpChoice在C#项目中使用type.我创造了一个这样的选择
var a = FSharpChoice<T1,T2,T3>.NewChoice1Of3(instofT1);
Run Code Online (Sandbox Code Playgroud)
现在我如何instofT1摆脱选择类型.
我看到我可以做一个,IsChoice1Of3但我如何得到选择对象中的值?
我可能不会直接使用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).