波苏斯
一些最简单的类是 POCO。
// C#
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Birthday { get; set; }
}
在 F#3.0 中,引入了类似于 C#auto-properties 的自动属性,
// F#
type Person() =
member val FirstName = "" with get, set
member val LastName = "" with get, set
member val BirthDay = System.DateTime.Today with get, set
创建任一个实例都是类似的,
// C#
var person = new Person { FirstName = "Bob", LastName = "Smith", Birthday = DateTime.Today };
// F#
let person = new Person(FirstName = "Bob", LastName = "Smith")
如果你可以使用不可变值,则记录类型更加惯用 F#。
type Person = {
FirstName:string;
LastName:string;
Birthday:System.DateTime
}
并且可以创建此记录:
let person = { FirstName = "Bob"; LastName = "Smith"; Birthday = System.DateTime.Today }
也可以通过指定现有记录并添加 with
,然后添加要覆盖的字段列表,根据其他记录创建记录:
let formal = { person with FirstName = "Robert" }