【问题标题】:F#: Trying to support passing a function in a constructor in both F# and C# idiomsF#:尝试在 F# 和 C# 习惯用法中支持在构造函数中传递函数
【发布时间】:2014-06-09 06:27:16
【问题描述】:

我的类型:

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 -&gt; bool) -&gt; MyType, new : myFn:Func&lt;bool&gt; -&gt; MyType

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

【问题讨论】:

    标签: c# constructor f# overloading


    【解决方案1】:

    如果 F# 接受 Func&lt;bool&gt; 委托,它将能够调用构造函数。因此,使用 Func&lt;bool&gt; 的单个重载应该适用于 C# 和 F#:

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

    【讨论】:

      猜你喜欢
      • 2010-09-07
      • 1970-01-01
      • 1970-01-01
      • 2014-03-25
      • 1970-01-01
      • 2018-09-20
      • 1970-01-01
      • 1970-01-01
      • 2016-05-16
      相关资源
      最近更新 更多