为什么这种类型不是接口?
Why this type is not an Interface?
我想为相等和比较函数创建一个默认实现的接口。
如果我从类型 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<'A>
作为接口,以便 "gain" 相等和比较的默认实现。
错误消息出现在类型 Operation
下的 interface ... with
上:The type 'IKeyable<Guid>' is not an interface type
接口不能有方法实现,而您的类型有五个方法实现 - Equals
、GetHashCode
、IEquatable<_>.Equals
、IComparable<_>.CompareTo
和 IComparable.CompareTo
.
接口纯粹是一组方法和属性。它不像一个基础 class,它不能给实现者一些 "default" 实现或基础行为或实用方法之类的东西。
要使您的类型成为接口,请摆脱所有实现:
type IKeyable<'A when 'A: equality and 'A :> IComparable> =
inherit IEquatable<'A>
inherit IComparable<'A>
abstract member Key : 'A
如果你真的想保留默认实现,你必须使它成为基础 class 而不是接口,在这种情况下 Operation
必须成为 class 而不是记录:
type Operation(id: Guid)
inherit IKeyable<Guid>
override this.Key = id
member val Id = id
我想为相等和比较函数创建一个默认实现的接口。
如果我从类型 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<'A>
作为接口,以便 "gain" 相等和比较的默认实现。
错误消息出现在类型 Operation
下的 interface ... with
上:The type 'IKeyable<Guid>' is not an interface type
接口不能有方法实现,而您的类型有五个方法实现 - Equals
、GetHashCode
、IEquatable<_>.Equals
、IComparable<_>.CompareTo
和 IComparable.CompareTo
.
接口纯粹是一组方法和属性。它不像一个基础 class,它不能给实现者一些 "default" 实现或基础行为或实用方法之类的东西。
要使您的类型成为接口,请摆脱所有实现:
type IKeyable<'A when 'A: equality and 'A :> IComparable> =
inherit IEquatable<'A>
inherit IComparable<'A>
abstract member Key : 'A
如果你真的想保留默认实现,你必须使它成为基础 class 而不是接口,在这种情况下 Operation
必须成为 class 而不是记录:
type Operation(id: Guid)
inherit IKeyable<Guid>
override this.Key = id
member val Id = id