【发布时间】:2021-06-04 16:07:44
【问题描述】:
我有一个 C# 类,它的方法带有几个引发异常的可选参数。我想捕获异常并返回结果,同时保持提供可选参数的能力。有没有办法使用多个可选参数来做到这一点,而不会在匹配表达式中创建大量案例?
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 并且只使用所有参数调用内部方法,但我不一定知道包装方法的默认值是什么(或者是否有办法提取它们)并且不想改变默认行为。
【问题讨论】:
标签: f#