Object initialization syntax

旧巷老猫 提交于 2019-11-28 04:01:58
CMS

You can do it like this:

let p = new Person (Name = "John", BirthDate = DateTime.Now)

the answer from CMS is definitely correct. Here is just one addition that may be also helpful. In F#, you often want to write the type just using immutable properties. When using the "object initializer" syntax, the properties have to be mutable. An alternative in F# is to use named arguments, which gives you a similar syntax, but keeps things immutable:

type Person(name:string, ?birthDate) =
  member x.Name = name
  member x.BirthDate = defaultArg birthDate System.DateTime.MinValue

Now we can write:

let p1 = new Person(name="John", birthDate=DateTime.Now)
let p2 = new Person(name="John")

The code requires you to specify the name, but birthday is an optional argument with some default value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!