gpt4 book ai didi

inheritance - f# 类型提供程序继承

转载 作者:行者123 更新时间:2023-12-04 08:51:28 25 4
gpt4 key购买 nike

我设计了一个简单的类型提供程序,它根据我的参数提供类型。我想知道是否可以定义会继承另一个 ProvidedTypeDefinition 的 ProvidedTypeDefinition?

我知道静态我可以执行以下操作:

type People() = class end

type Student() =
inherit People()

type Teacher() =
inherit People()

然后我可以使用类型测试模式进行模式匹配:
let f (x:People) =
match x with
| :? Student -> "Student"
| :? Teacher -> "Teacher"
| _ -> "Nothing !!"

我想在我的类型提供程序中做的是创建继承另一个 ProvidedTypeDefinition 的 ProvidedTypeDefinition。这样,当我使用类型提供程序生成这些类型时,我可以对它们进行模式匹配(例如,我知道在运行时将实例化这种类型之一,但我不知道是哪一个,除了它是 ProvidedTypeDefinitions 之一)。

感谢您的时间!

最佳答案

尝试使用 Discriminated Union 进行模式匹配而不是继承

type Occupation =
| Student
| Teacher

type People(occupation) =
member this.Occupation = occupation
class end

type Student() =
inherit People(Student)

type Teacher() =
inherit People(Teacher)

let findPerson (person : People) =
match person.Occupation with
| Student -> "Student"
| Teacher -> "Teacher"

我个人喜欢避免在 fsharp 中使用对象继承,因为 upcasting and downcasting .例如,
let person = new Student() :> People
findPerson person

相反,我建议摆脱学生和老师的解析,让人们处理职业逻辑。
type Occupation =
| Student
| Teacher

type People(occupation) =
member this.Occupation = occupation
class end

let findPerson (person : People) =
match person.Occupation with
| Student -> "Student"
| Teacher -> "Teacher"

People Student
|> findPerson
|> printfn "%s"

关于inheritance - f# 类型提供程序继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37336201/

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