【问题标题】:a pitfall in argument and interface inheritance in fsharpfsharp 中参数和接口继承的一个陷阱
【发布时间】:2014-07-11 20:14:53
【问题描述】:

KO 不工作有什么真正的原因吗?

  type IBase = 
      abstract member test : (unit * unit) -> unit

  type OK() = 
      interface IBase with

        member x.test ((titi,tata)) = () //OK

  type KO() = 
      interface IBase with

        member x.test (titi,tata) = () //fail : This override takes a different number of arguments to the corresponding abstract member    

【问题讨论】:

    标签: f# unit-type


    【解决方案1】:

    因为括号意思在F#中是什么意思(它表示一个元组),所以它们不一样。

    如给定的那样,test 方法被定义为将两个unit 值的元组 作为参数的方法。如果使用Reflection获取MethodInfo,则方法定义为:

    Void test(System.Tuple`2[Microsoft.FSharp.Core.Unit,Microsoft.FSharp.Core.Unit])
    

    这与OK 方法匹配,但与KO 方法不匹配。

    如果将接口重新定义为

    type IBase = 
        abstract member test : unit * unit -> unit
    

    那么OK 不会编译,但KO 会。

    这个替代版本产生一个test 方法,它接受两个参数:

    Void test(Microsoft.FSharp.Core.Unit, Microsoft.FSharp.Core.Unit)
    

    【讨论】:

    • repl 不正确吗?这是它为OK 类提供的类型:type OK = class interface IBase new : unit -> OK end
    • 一点也不。它告诉你的是OK 是一个实现接口IBase 并具有成员new 的类,它将unit 作为输入并返回OK 作为输出——这个成员也在OO称为构造函数;与IBase接口无关。
    • 不,我必须自己重温一遍 :)
    • 在子类定义中没有显示成员的覆盖,这有点烦人。
    【解决方案2】:
    abstract member test : (unit * unit) -> unit
    

    括号可用于对复杂参数进行分组,例如当一个 函数类型是一个参数,或指示何时处理元组 作为单个参数而不是作为两个参数。 http://msdn.microsoft.com/en-us/library/dd483468.aspx

    由于括号,您的抽象方法需要一个参数,该参数是 2 个单位的元组,而不是 2 个单位参数

    您可以将抽象方法定义为:

    abstract member test : unit * unit -> unit
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-17
      • 2013-10-22
      • 1970-01-01
      • 2014-03-09
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 2010-09-21
      相关资源
      最近更新 更多