相关疑难解决方法(0)

如何在F#中编写此成员约束?

对于一种类型

type Cow() =
    class
        member this.Walk () = Console.WriteLine("The cow walks.")
    end
Run Code Online (Sandbox Code Playgroud)

我可以编写一个方法来强制执行成员约束方法Walk

let inline walk_the_creature creature =  
    (^a : (member Walk : unit -> unit) creature)
// and then do
walk_the_creature (Cow())
Run Code Online (Sandbox Code Playgroud)

在这种情况下,推断出类型.我无法像这样明确地在creature参数上写一个约束

// Does not compile
// Lookup on object of indeterminate type based on information prior to this 
// program point. A type annotation may be needed...
let inline walk_the_creature_2 (creature:^a when ^a:(member Walk : unit -> unit)) =
    creature.Walk()
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

generics f#

16
推荐指数
1
解决办法
1572
查看次数

标签 统计

f# ×1

generics ×1