gpt4 book ai didi

f# - 有没有办法让记录继承 F# 中的抽象类?

转载 作者:行者123 更新时间:2023-12-04 23:02:53 24 4
gpt4 key购买 nike

假设我有一个接口(interface) IEvent .这个接口(interface)有一个 Id我在 C# 中使用以下实现的属性:

public abstract class EventBase : IEvent
{
public Guid Id { get; protected set; }
]

有没有办法在 F# 记录中继承这个抽象类?

就像是:
type OneOfMyEvents = {Id: Guid, Prop: string}
inherit EventBase(Id)

问题是我想将我的所有事件定义为记录,因为它真的很方便,但我也想强制我的所有事件都具有我不必每次都输入的 Id 属性。

最佳答案

记录不能从类继承,但它们可以实现接口(interface)。例如,使用您的 IEvent界面:

open System

[<Interface>]
type IEvent =
abstract Id : Guid with get


type MyRecord = {
Id: Guid;
Prop: string;
} with
interface IEvent with
member this.Id
with get () = this.Id

关于f# - 有没有办法让记录继承 F# 中的抽象类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22517957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com