【问题标题】:Why this type is not an Interface?为什么这种类型不是接口?
【发布时间】:2019-12-23 05:58:08
【问题描述】:

我想为相等和比较函数创建一个默认实现的接口。

如果我从IKeyable<'A> 类型中删除除Key 成员之外的所有内容,只要我不添加默认实现,它就是一个有效接口。从IKeyable<'A> 中删除其他接口实现,只保留默认成员会得到相同的结果。

type IKeyable<'A when 'A: equality and 'A :> IComparable> = 
    abstract member Key : 'A

    default this.Equals obj = // hidden for clarity

    default this.GetHashCode () = // hidden for clarity

    interface IEquatable<'A> with
        member this.Equals otherKey = // hidden for clarity

    interface IComparable<'A> with
        member this.CompareTo otherKey = // hidden for clarity

    interface IComparable with
        member this.CompareTo obj = // hidden for clarity

type Operation = 
    { Id: Guid }
    interface IKeyable<Guid> with // Error: The type 'IKeyable<Guid>' is not an interface type
        member this.Key = this.Id

我想使用IKeyable&lt;'A&gt; 作为接口,以便“获得”相等和比较的默认实现。

错误消息出现在interface ... with 类型Operation 下:The type 'IKeyable&lt;Guid&gt;' is not an interface type

【问题讨论】:

    标签: interface f# default-method


    【解决方案1】:

    一个接口不能有方法实现,你的类型有五个——EqualsGetHashCodeIEquatable&lt;_&gt;.EqualsIComparable&lt;_&gt;.CompareToIComparable.CompareTo

    接口纯粹是一组方法和属性。它不像基类,它不能为实现者提供一些“默认”实现或基本行为或实用方法。

    要使您的类型成为接口,请摆脱所有实现:

    type IKeyable<'A when 'A: equality and 'A :> IComparable> = 
        inherit IEquatable<'A>
        inherit IComparable<'A>
        abstract member Key : 'A
    

    如果您真的想保留默认实现,则必须将其设为基类而不是接口,在这种情况下,Operation 必须成为类而不是记录:

    type Operation(id: Guid)
        inherit IKeyable<Guid>
        override this.Key = id
        member val Id = id
    

    【讨论】:

    • 谢谢,我认为可以使用默认实现,因为:However, you can provide a default implementation by also including a separate definition of the member as a method together with the default keyword,来源:dotnet docs
    • 该陈述在技术上是正确的,因为您可以使用抽象成员来做到这一点。但它不适用于接口。这看起来像是文档中的错误。
    猜你喜欢
    • 2018-12-29
    • 2011-01-03
    • 2014-11-06
    • 2012-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    • 1970-01-01
    相关资源
    最近更新 更多