对象初始化语法

我刚刚开始使用 F # ,我找不到像 C # 3那样进行对象初始化的语法。

也就是说:

public class Person {
public DateTime BirthDate { get; set; }
public string Name { get; set; }
}

如何在 F # 中写下面的代码:

var p = new Person { Name = "John", BirthDate = DateTime.Now };
20335 次浏览

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.

You can also omit the new keyword and use less verbose syntax:

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

https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/members/constructors