我的理解是F#记录是非密封类.如果是这样,我可以继承记录类型吗?例如:
type person = {name:string; address:string}
type employee inherit person = {employeeId: string}
Run Code Online (Sandbox Code Playgroud)
我搜索了MSDN文档和语言规范,我没有运气.提前致谢
Tom*_*cek 21
F#记录不能被继承 - 正如Matthew所提到的,它们被编译为密封类,但它也是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
Run Code Online (Sandbox Code Playgroud)
我认为首选的选择是使用组合而不是继承,并使员工成为由一些个人信息和ID组成的记录:
type PersonalInformation = { Name : string }
type Employee =
{ Person : PersonalInformation
ID : int }
Run Code Online (Sandbox Code Playgroud)
我可能不会让一个人成为员工的一部分(这对我来说不合适,但这只是一种直觉),这就是我将其重命名为此的原因PersonalInformation.
我想另一个选择是IPerson作为一个接口,并有一个实现该接口的记录 Employee:
type IPerson =
abstract Name : string
type Employee =
{ ID : int
Name : string }
interface IPerson with
member x.Name = x.Name
Run Code Online (Sandbox Code Playgroud)
哪一个最好真的取决于你正在建模的具体事物.但我认为F#中通常首选接口和组合:-)
它们是密封类,这是为该类生成的类的前几行person:
[CompilationMapping(SourceConstructFlags.RecordType)]
[Serializable]
public sealed class person
: IEquatable<person>,
IStructuralEquatable,
IComparable<person>,
IComparable,
IStructuralComparable
Run Code Online (Sandbox Code Playgroud)