[英]Object initializer + property initializer (from C# to F#)
I have a Person and I want initialize the Name with the property initializer and the Age with the constructor. 我有一个Person,我希望使用属性初始值设定项初始化Name,使用构造函数初始化Age。
C# version C#版本
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(int age)
{
Age = age
}
}
var person = new Person(20) { Name = "Alex" };
I've tried with F#: 我试过F#:
Try 1: Invalid syntax 尝试1:语法无效
type Person = {
Name: string
Age: int
} with
static member create (age: int): Person =
{ this with Age = age }: Person
Try 2: Invalid syntax 尝试2:语法无效
type Person =
member val Name: string
member val Age: int
new(age: int)
this.Age = 13
Should be as simple as 应该如此简单
type Person(age:int) =
member val Name = "" with get, set
member val Age = age with get, set
let person = Person(20, Name = "Alex")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.