f#向对象表达式添加非接口函数

时间:2016-02-01 21:29:05

标签: f#

假设我有一个接口ICache,它定义了两个函数Function1Function2,我使用一个对象表达式来实现它,但我还想添加一个辅助函数:< / p>

let WebCache =
    {    new ICache with
         member __.HelperFunction = //this doesn't work!
         member __.Function1 = foo
         member __.Function2 = bar
    }

F#似乎不允许您添加任何不属于该接口的方法。有解决方法吗?如果我想这样做,我首先应该不使用对象表达式吗?

1 个答案:

答案 0 :(得分:3)

您可以将辅助函数定义为对象表达式之外的普通(本地)函数:

let WebCache =
    let helper n = 
         printfn "Helping %" n
    { new ICache with
         member __.Function1 = helper 1
         member __.Function2 = helper 2 }