通过对象表达式扩展带有接口的对象

时间:2014-07-08 21:25:53

标签: f#

是否可以使用对象表达式使用接口装饰F#中的对象。 E.g:

type IFoo = abstract member foo : string
type IBar = abstract member bar : string
let a = { new IFoo with member x.foo = "foo" }

/// Looking for a variation on the below that does compile, the below doesn't
let b = { a with
             interface IBar with
                 member x.Bar = "bar" }

1 个答案:

答案 0 :(得分:4)

您无法在运行时使用接口扩展对象,但可以使用其他对象包装它:

let makeB (a: IFoo) = 
    { 
        new IFoo with
            member x.foo = a.foo
        interface IBar with
            member x.bar = "bar" 
    }


let a = { new IFoo with member x.foo = "foo" }
let b = makeB a