我不记得如何让 SRTP 发挥作用了
我想要一个接受参数并调用指定方法的函数,简单吗?
let inline YearDuck< ^a when ^a : (member Year : Unit -> string)> (x : ^a) : string =
x.Year ()
Run Code Online (Sandbox Code Playgroud)
但我明白了
Severity Code Description Project File Line Suppression State
Error FS0072 Lookup on object of indeterminate type based on information prior to this program point. A type annotation may be needed prior to this program point to constrain the type of the object. This may allow the lookup to be resolved.
Run Code Online (Sandbox Code Playgroud)
它知道 x 是一个 ^a,我已经指定 ^a 有方法 Year,那么问题是什么?
(其实我想让Year成为一个属性,但我以为我会先走再跑)
尝试用这种方法代替:
let inline YearDuck x =
(^a : (member Year : unit -> string) x)
Run Code Online (Sandbox Code Playgroud)
测试代码:
open System
type YearTest (dt : DateTime) =
member _.Year() = string dt.Year
YearTest(DateTime.Now)
|> YearDuck
|> printfn "%A" // "2022"
Run Code Online (Sandbox Code Playgroud)
我希望我能说出为什么它会以这种方式工作,而不是按照您尝试的方式工作,但我真的不知道,而且我认为任何地方都没有明确记录。SRTP 目前的形式只是黑魔法。
如果您想要房产,请尝试以下操作:
let inline YearDuck x =
(^a : (member get_Year : unit -> string) x)
type YearTest (dt : DateTime) =
member _.Year = string dt.Year
YearTest(DateTime.Now)
|> YearDuck
|> printfn "%A" // "2022"
Run Code Online (Sandbox Code Playgroud)