【问题标题】:Wrappers around methods with multiple optional parameters具有多个可选参数的方法的包装器
【发布时间】: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#


    【解决方案1】:

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

    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 也很容易找到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-22
      • 2017-05-06
      • 2014-01-09
      • 2016-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多