【发布时间】:2015-05-18 13:07:35
【问题描述】:
请解释drawShape 函数背后的魔力。 1) 为什么它会起作用 -- 我的意思是它如何调用 Draw 成员,2) 为什么它需要是 inline?
type Triangle() =
member x.Draw() = printfn "Drawing triangle"
type Rectangle() =
member x.Draw() = printfn "Drawing rectangle"
let inline drawShape (shape : ^a) =
(^a : (member Draw : unit->unit) shape)
let triangle = Triangle()
let rect = Rectangle()
drawShape triangle
drawShape rect
下一个问题是——是否可以使用下面的参数类型注释来编写drawShape 函数?我发现它的签名与第一个完全相同,但我无法完成正文。
let inline drawShape2 (shape : ^a when ^a : (member Draw : unit->unit)) =
...
提前致谢。
【问题讨论】:
-
魔力全在 F# 编译器中 - 不知道该说什么 - 对于您的第二个问题:如果没有看到正文/错误,您很难分辨
-
我尝试将
shape.Draw()放入正文中但没有成功。错误是:error FS0072: Lookup on object of indeterminate type based on information prior to this program point. A type annotation may be needed prior to this program point to constrain the type of the object. This may allow the lookup to be resolved. -
啊,我明白了 - 很遗憾,您必须再次重复您在
drawShap中所做的相同操作((^a : (member Draw : ...) shape)中的部分 -
只是对此的评论:恕我直言,你真的应该只在绝对需要时才使用这个功能 - 在这里它会更容易拥有
IDrawable接口与抽象Draw方法代替。 -
这正是我想要避免的——OO 启发的显式接口。 ;-)
标签: f#