gpt4 book ai didi

inheritance - 我可以避免为派生自接口(interface)的类编写样板代码吗?

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

我有很多实现接口(interface)的类。每当我定义一个类时,我都必须在类定义中写这样的东西:

interface Model.IModel with

member this.Assets = modelArg.Assets
member this.AuxData = modelArg.AuxData
member this.Benchmark = modelArg.Benchmark
member this.CalcPeriods = modelArg.CalcPeriods
member this.CashTicker = modelArg.CashTicker
member this.Description = modelArg.Description
member this.FirstValidDate = modelArg.FirstValidDate
member this.Name = modelArg.Name
member this.ParamData = modelArg.ParamData
member this.ParamList = modelArg.ParamList
member this.Strategy = modelArg.Strategy

member this.CalcStartTime with get() = calcStartTime and
set v = calcStartTime <- v

member this.Counter with get() = counter and
set v = counter <- v

有没有办法避免对从接口(interface) IModel 派生的每个类重复此操作?代码在所有情况下都是相同的。

最佳答案

为了使讨论更具体一些,并且由于评论中的空间有限,下面的内容是否适合您?

 type ModelArg = {
Number: int
Name: string
}

type IModel(modelArg: ModelArg) =
abstract member Number: int
abstract member Name: string
default __.Number = modelArg.Number
default __.Name = modelArg.Name

type ConcreteModel1(modelArg: ModelArg) =
inherit IModel(modelArg)

type ConcreteModel2(modelArg: ModelArg) =
inherit IModel(modelArg)

let modelArg1 = {Number=2; Name ="Joe"}
let modelArg2 = {Number=3; Name = "Jim"}

let getNumberAndName(x: IModel) =
(x.Number, x.Name)

let model1 = ConcreteModel1(modelArg1)
let model2 = ConcreteModel2(modelArg2)

getNumberAndName(model1)
//val it : int * string = (2, "Joe")
getNumberAndName(model2)
//val it : int * string = (3, "Jim")

关于inheritance - 我可以避免为派生自接口(interface)的类编写样板代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50239493/

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