gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:20:54 25 4
gpt4 key购买 nike

对于类型

type Cow() =
class
member this.Walk () = Console.WriteLine("The cow walks.")
end

我可以编写一个方法来强制方法 Walk 的成员约束,例如

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

在这种情况下,类型是推断出来的。我无法像这样显式地编写对生物参数的约束

// 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()

我做错了什么?

最佳答案

问题并不是明确地编写约束,而是语法不太好,您可以在参数上放置成员约束,然后以通常的方式调用该成员。 walk_the_creaturewalk_the_creature2 的主体在这里是相同的:

let inline walk_the_creature_2 (creature:^a when ^a:(member Walk : unit -> unit)) =
(^a : (member Walk : unit -> unit) creature)

关于generics - 如何在 F# 中编写此成员约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4694633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com