【问题标题】:F# new type that is extension of old typeF# 新类型是旧类型的扩展
【发布时间】:2021-05-11 19:32:22
【问题描述】:

假设我有一个员工类型

type employee = {
    employee_id: int
    name: string 
    department: int
}

type department = {
   department_id: int
   department_name: string
}

我想要第二种类型,它既包括员工类型中的所有内容,也包括部门类型中的所有内容(实际上是 SQL 连接的结果)。

例如

type employee_extended = {
    employee_id: int
    name: string 
    department: int
    department_id: int
    department_name: string
}

实际上,我有更多列的表,所以只是想知道是否有定义扩展类型的简写:) 可以假设没有重复的属性名称,但如果可以处理它们,将来可能会有用。

【问题讨论】:

标签: f#


【解决方案1】:

如果您有两种类型(员工和部门)的一些数据,并且想要创建一个包含有关员工和部门的信息的新类型,最好的方法是定义一个包含其他两种类型的新记录类型作为字段:

type Employee = {
    EmployeeId: int
    Name: string 
    Department: int
}

type Department = {
   DepartmentId: int
   Department_name: string
}

// New type containing information about 
// an employee and also their department
type EmployeeWithDepartment = {
  Employee : Employee
  Department : Department
}

【讨论】:

  • 也许值得一提的是,如果组合类型感觉做作,您可以简单地使用元组 (Employee*Department) 或匿名类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-11
  • 2013-08-04
相关资源
最近更新 更多