对象初始化器+属性初始化器(从C#到F#)

时间:2017-09-20 20:19:40

标签: class oop f#

我有一个Person,我希望使用属性初始值设定项初始化Name,使用构造函数初始化Age。

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" };

我试过F#:

尝试1:语法无效

type Person = {
    Name: string
    Age: int
} with 
    static member create (age: int): Person =
        { this with Age = age }: Person

尝试2:语法无效

type Person =
    member val Name: string
    member val Age: int

    new(age: int)
        this.Age = 13

1 个答案:

答案 0 :(得分:6)

应该像

一样简单
type Person(age:int) =
    member val Name = "" with get, set
    member val Age = age with get, set

let person = Person(20, Name = "Alex")