📜  F#类型扩展

📅  最后修改于: 2021-01-01 14:37:01             🧑  作者: Mango

F#类型扩展

类型扩展允许您将新成员添加到先前定义的对象类型。

F#语言中的类型扩展的语法如下:

// Intrinsic extension.
type typename with
    member self-identifier.member-name =
        body
    ...
[ end ]

// Optional extension.
type typename with
    member self-identifier.member-name =
        body
    ...
[ end ]

F#类型扩展示例

在下面的示例中,我们将新方法添加到先前定义的类中。在这里,我们通过使用类的单个对象来调用方法。

type ClassExtension() =
 member this.ShowBefore() = printfn"Class before extension"

// Define type extension.
type ClassExtension with
 member this.ShowAfter() = printfn"Class after extension"

let classExtension = new ClassExtension()
classExtension.ShowBefore()
classExtension.ShowAfter()

输出:

Class before extension
Class after extension