如何在 F# 中编写此成员约束? [英] How do I write this member constraint in F#?

查看:13
本文介绍了如何在 F# 中编写此成员约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个类型

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

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

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

我做错了什么?

推荐答案

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

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# 中编写此成员约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆