包装具有多个可选参数的方法

Wrappers around methods with multiple optional parameters

我有一个 C# Class,其方法带有多个可选参数,会引发异常。我想捕获异常并 return 结果,同时保持提供可选参数的能力。有没有办法在不在匹配表达式中创建大量情况的情况下使用多个可选参数来做到这一点?

type SomeType with
    member this.DoSomethingResult(?a, ?b:, ?c) =
            try
                let x =
                    match a, b, c with
                    | None, None, None -> this.DoSomething()
                    | Some a, None, None -> this.DoSomething(a)
                    | Some a, Some b, None -> this.DoSomething(a, b)
                    | Some a, None, Some c -> this.DoSomething(a, c = c)
                    | Some a, Some b, Some c -> this.DoSomething(a, b, c)
                    | None, Some b, None -> this.DoSomething(b = b)
                    | None, Some b, Some c -> this.DoSomething(b = b, c = c)
                    | None, None, Some c -> this.DoSomething(c = c)

                Ok x
            with ex -> Error ex.Message

案例数量与参数数量的阶乘成正比,因此对于超过 3 个参数,这显然不是一个可行的模式,甚至是推动它。 我考虑过使用 defaultArg 并且只调用带有所有参数的内部方法,但我不一定知道包装方法的默认值是什么(或者是否有提取它们的方法)并且不想改变默认行为。

This 答案提供了解决方案的提示,但我找不到专门解决此问题的问题。诀窍是在内部方法调用中使用可选的命名参数:

type SomeType with
    member this.DoSomethingResult(?a, ?b:, ?c) =
            try
                let x = this.DoSomething(?a = a, ?b = b, ?c = c)
                Ok x
            with ex -> Error ex.Message

找到解决方案后,相关的Microsoft docs也很容易找到。