本文介绍了我如何在F#中编写此成员约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于类型 类型Cow()=
class
member this.Walk() = Console.WriteLine(The cow walks。)
end
我可以写一个方法强制成员约束的方法Walk像
let inline walk_the_creature creature =
(^ a:(member Walk :unit - > unit)creature)
//然后做
walk_the_creature(Cow())
在这种情况下,推断类型。我无法明确地写出这样的生物参数约束。
//不编译
//查找基于这个
//程序点之前的信息的不确定类型的对象。可能需要类型注释...
let inline walk_the_creature_2(生物:^ a当^ a :(成员步行:单位 - >单位))=
creature.Walk()
我做错了什么?
解决方案
它没有明确写出约束是问题,而是语法不够好,您可以将一个成员约束放在一个参数上,然后以通常的方式调用该成员。 walk_the_creature
和 walk_the_creature2
的主体在这里是一样的:
let inline walk_the_creature_2(生物:^ a当^ a :(成员Walk:单位 - >单位))=
(^ a :(成员Walk:单位 - >单位)生物)
For a type
type Cow() =
class
member this.Walk () = Console.WriteLine("The cow walks.")
end
I can write a method which enforces a member constrain for method Walk like
let inline walk_the_creature creature =
(^a : (member Walk : unit -> unit) creature)
// and then do
walk_the_creature (Cow())
In this case the type is inferred. I am unable to explicitly write a constraint on the creature parameter like this
// 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()
What am I doing wrong?
解决方案
It's not explicitly writing the constraints that is the issue, it's that the syntax is not so nice that you can place a member constraint on a parameter and then invoke the member in the usual way. The body of walk_the_creature
and walk_the_creature2
would be the same here:
let inline walk_the_creature_2 (creature:^a when ^a:(member Walk : unit -> unit)) =
(^a : (member Walk : unit -> unit) creature)
这篇关于我如何在F#中编写此成员约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!