[英]F#: Member constraints to help create seemingly dynamic types
I've been looking into a way to add some duck typing to an F# method. 我一直在寻找一种方法来为F#方法添加一些鸭子类型。
SomeMethod(model:'a) =
let someField = model.Test("")
Where the parameter coming in has the Test method on it. 进来的参数有Test方法。 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?
这是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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.