使用对象表达式创建接口类型时覆盖ToString

时间:2010-11-08 16:37:49

标签: f#

在使用对象表达式创建接口类型时,有没有办法覆盖System.Object的虚方法,尤其是ToString

type INamedObject =
    abstract Name : string

let makeNamedObject name = 
    { new INamedObject with
        member x.Name = name
        override x.ToString() = x.Name } //would like to do this, but doesn't work

1 个答案:

答案 0 :(得分:5)

可以在包含具体类型的对象表达式中提供多种类型来实现/覆盖。这允许您在表达式中指定ObjectINamedObject并获得所需的效果。

let makeNamedObject name =  
    { 
        new System.Object() with 
            member x.ToString() = name
        interface INamedObject with
            member x.Name = name  }