2014-12-02 53 views
5

我的理解是F#记录是非密封类。如果是这样,我可以继承一个记录类型吗?例如:继承F#记录

type person = {name:string; address:string} 
type employee inherit person = {employeeId: string} 

我有搜索MSDN文档和语言规范,我没有任何运气。 在此先感谢

+0

Offtopic,但不要让员工继承人:-) – 2014-12-02 15:16:15

+0

我现在有这个权利:employee {person:Person;根据Tomas P.,这是正确的。我只是看到了如何去做。 :-) – 2014-12-02 15:18:55

回答

20

F#记录不能被继承 - 马修提到,他们被编译成密封类,但它也是F#类型系统的一个方面,它根本不允许这样做。

实际上,您可以使用普通的类声明。这意味着您将无法使用{ person with ... }语法,你不会得到自动结构性平等的,但如果你想创建C#代码 - 友好它可能是有意义:

type Person(name:string) = 
    member x.Name = name 

type Employee(name:string, id:int) = 
    inherit Person(name) 
    member x.ID = id 

我觉得较好的选择是使用组成而不是继承和使员工一说是由一些个人信息和ID记录:

type PersonalInformation = { Name : string } 

type Employee = 
    { Person : PersonalInformation 
    ID : int } 

我可能不会做相提并论t的雇员(这不适合我,但这只是一个直觉),这就是为什么我把它改名为PersonalInformation在这里。

我想另一种选择是将有IPerson为一个接口,有一个记录Employee实现接口:

type IPerson = 
    abstract Name : string 

type Employee = 
    { ID : int 
    Name : string } 
    interface IPerson with 
    member x.Name = x.Name 

哪一个是最好的真的取决于你是建模具体的东西。但我认为界面和组成通常是F#中的首选:-)

8

它们密封类,下面是对person生成的类的前几行:

[CompilationMapping(SourceConstructFlags.RecordType)] 
[Serializable] 
public sealed class person 
: IEquatable<person>, 
    IStructuralEquatable, 
    IComparable<person>, 
    IComparable, 
    IStructuralComparable