sách gpt4 ai đã đi

Tại sao loại này không phải là giao diện?

In lại 作者:行者123 更新时间:2023-12-03 00:01:31 44 4
mua khóa gpt4 Nike

我想创建一个具有相等和比较函数默认实现的接口(interface)。

如果我从类型 IKeyable<'A> 中删除所有内容除了Chìa khóa成员,只要我不添加默认实现,它就是一个有效的接口(interface)。从 IKeyable<'A> 中删除其他接口(interface)实现,并且仅保留默认成员会得到相同的结果。

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 with // Error: The type 'IKeyable' is not an interface type
member this.Key = this.Id

我想使用IKeyable<'A>作为一个接口(interface),以便“获得”相等和比较的默认实现。

interface ... with 上出现错误消息在类型Operation下:The type 'IKeyable' is not an interface type

1 Câu trả lời

接口(interface)不能有方法实现,而您的类型有五个方法实现 - Equals , GetHashCode , IEquatable<_>.Equals , IComparable<_>.CompareTo ,和IComparable.CompareTo .

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

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

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

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

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

关于interface - 为什么这个类型不是接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57532604/

44 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com