F#:会员约束来帮助创建看似动态的类型 [英] F#: Member constraints to help create seemingly dynamic types

查看:99
本文介绍了F#:会员约束来帮助创建看似动态的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种方法来为F#方法添加一些鸭子打字。

I've been looking into a way to add some duck typing to an F# method.

SomeMethod(model:'a) =
   let someField = model.Test("")

其中的参数有Test方法。我见过这样的记法:

Where the parameter coming in has the Test method on it. I've seen notation like this:

member inline public x.Testing< ^a when ^a : (member public Test : String-> String)>(model:^a) =   
  let something = model.Test("")
  ignore

在我看来,通用约束可以用于方法级别而不是类/接口级别。问题是由于类型问题,我无法编译它。这使我相信,没有办法在方法级别指定约束。

Which looks like to me that generic constraints can be used to enfore at a method level rather than class/interface level. Problem is I can't get it to compile due to type issues. This leads me to believe that there isn't a way to specify constraints at the method level. Is that coorect?

推荐答案

这个语法有点笨拙,但在这里。

The syntax for this is a bit clunky, but here it is.

type Foo() =
  member inline public x.Testing(model) =   
    let something = (^a : (member Test : string -> string) (model, ""))
    ignore

重新使用接口可能会更好:

You're probably better off using an interface:

type IModel
  abstract Test : string -> string

这篇关于F#:会员约束来帮助创建看似动态的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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