在使用对象表达式创建接口类型时,有没有办法覆盖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
答案 0 :(得分:5)
可以在包含具体类型的对象表达式中提供多种类型来实现/覆盖。这允许您在表达式中指定Object
和INamedObject
并获得所需的效果。
let makeNamedObject name =
{
new System.Object() with
member x.ToString() = name
interface INamedObject with
member x.Name = name }