inheritance - 传播可选参数

标签 inheritance f# optional-arguments

以下代码无法编译。

type A(?arg) =
  member __.Arg : string option = arg

type B(?arg) =
  inherit A(arg) //ERROR expected type string but has type 'a option

我认为这是因为必须提供选项的底层类型的实例,并且编译器处理传递 Some/None基于语法。

假设我的假设已被正确假设,是否有解决方法?是否可以传播可选参数?

最佳答案

F# 规范 8.13.5 方法成员的可选参数

Callers may specify values for optional arguments by using the following techniques:


  • 按名称,例如 arg2 = 1。
  • 通过按名称传播现有的可选值,例如 ?arg2=None 或 ?arg2=Some(3) 或 ?arg2=arg2。这在构建一个将可选参数传递给另一个的方法时很有用。
  • 通过使用按位置匹配的普通未命名参数。
    type A(?arg) =
        member __.Arg : string option = arg
    
    type B(?arg) =
        inherit A(?arg = arg) 
    
    printfn "1. %A" (B()).Arg // None
    printfn "2. %A" (B("1")).Arg // Some "1"
    
    printfn "3. %A" (A()).Arg // None
    printfn "4. %A" (A("1")).Arg // Some "1"
    
  • 关于inheritance - 传播可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7095620/

    相关文章:

    c++ - 非多态继承对性能/内存使用有影响吗?

    c++ - 使用派生类类型初始化模板类的静态数组

    haskell - 简单发电机

    javascript - 我是否需要将 null 作为参数传递给 Javascript 函数/方法中的可选参数?

    C++,继承,虚拟

    python - Django Rest框架-如何反序列化基于模型类名的序列化器?

    generics - F# 编译错误 : Unexpected type application

    f# - 您在 F# 中创建了哪些简单、重要、可用的代码

    kotlin - Kotlin和构造函数,初始化

    javascript - 在 JavaScript 中正确使用可选参数