是否可以将受约束的成员作为第一类函数(给定对象)进行访问?如果是这样,使用正确的语法是什么?
// Example: property getter as a first-class function
type Test() =
member x.Value = "42"
let t = Test()
let getter = t.get_Value // works as expected
// now generically:
let inline getGetter< ^a when ^a : (member get_Value : unit -> string)> item =
// call getter
let value = (^a : (member get_Value : unit -> string) item)
// try to get getter as first-class function
let getter = item.get_Value // doesn't compile: "Lookup on object of indeterminate type..."
()
答案 0 :(得分:6)
我认为这就是你要找的东西:
type Test() =
member x.Value = "42"
let inline getGetter< ^a when ^a : (member get_Value : unit -> string)> item =
fun () -> (^a : (member get_Value : unit -> string) item)
let t = Test()
let getter = getGetter t
let value = getter()