对象初始化语法

发布于 2024-07-09 16:50:50 字数 293 浏览 11 评论 0 原文

我刚刚开始使用 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 };

I'm just starting out with F# and I can't find the syntax to do object initialization like in C# 3.

I.e. given this:

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

how do I write the following in F#:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

半衬遮猫 2024-07-16 16:50:50

你可以这样做:

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

You can do it like this:

let p = new Person (Name = "John", BirthDate = DateTime.Now)
紙鸢 2024-07-16 16:50:50

CMS的答案绝对是正确的。 这里只是补充一项可能也有帮助的内容。 在 F# 中,您通常希望仅使用不可变属性来编写类型。 当使用“对象初始值设定项”语法时,属性必须是可变的。 F# 中的另一种选择是使用命名参数,它为您提供类似的语法,但保持事物不可变:

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

现在我们可以编写:

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

代码要求您指定名称,但生日是具有某些默认值的可选参数。

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.

您还可以省略 new 关键字并使用不太详细的语法:

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文