Object initializer + property initializer (from C# to F#)

萝らか妹 提交于 2019-12-23 16:27:47

问题


I have a Person and I want initialize the Name with the property initializer and the Age with the constructor.

C# version

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#:

Try 1: Invalid syntax

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

Try 2: Invalid syntax

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

    new(age: int)
        this.Age = 13

回答1:


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")


来源:https://stackoverflow.com/questions/46331134/object-initializer-property-initializer-from-c-sharp-to-f

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