Jea*_*pes 1 f# interface default-method
我想为默认函数实现一个相等和比较功能的接口。
如果我从成员中删除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
Run Code Online (Sandbox Code Playgroud)
我想将其IKeyable<'A>用作接口,以便“获得”用于相等性和比较的默认实现。
错误消息出现interface ... with在类型下 Operation:The type 'IKeyable<Guid>' is not an interface type
接口不能有方法的实现,和你的类型有其中五- ,Equals,GetHashCode,IEquatable<_>.Equals,IComparable<_>.CompareTo和IComparable.CompareTo。
接口纯粹是一组方法和属性。它不像基类,它不能给实现者一些“默认”实现,基本行为或实用程序方法。
要使您的类型成为接口,请摆脱所有实现:
type IKeyable<'A when 'A: equality and 'A :> IComparable> =
inherit IEquatable<'A>
inherit IComparable<'A>
abstract member Key : 'A
Run Code Online (Sandbox Code Playgroud)
如果您确实想保留默认的实现,则必须使其成为基类而不是接口,在这种情况下,Operation必须将其变为类而不是记录:
type Operation(id: Guid)
inherit IKeyable<Guid>
override this.Key = id
member val Id = id
Run Code Online (Sandbox Code Playgroud)