f#:尝试支持在构造函数中传递f#和c#习惯用法中的函数

本文关键字:习惯 惯用法 函数 支持 构造函数 | 更新日期: 2023-09-27 18:07:30

我的文字:

open System
type MyType (myFn : unit -> bool) =
    member this.MyResult with get () = myFn ()
    new (myFn : Func<bool>) = MyType (myFn.Invoke)

我得到的错误:

A unique overload for method 'MyType' could not be determined based on type information prior to this program point. A type annotation may be needed. Candidates: new : myFn:(unit -> bool) -> MyType, new : myFn:Func<bool> -> MyType

既然我已经提供了类型注释,它不起作用的真正原因是什么?

f#:尝试支持在构造函数中传递f#和c#习惯用法中的函数

f#将能够调用构造函数,如果它接受Func<bool>委托。因此,采用Func<bool>的单一过载应该适用于c#和f#:

open System
type MyType (myFn : Func<bool>) =
  member this.MyResult with get () = myFn.Invoke ()