波蘇斯
一些最簡單的類是 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" }