对象初始值设定项+属性初始值设定项(从C#到F#) [英] Object initializer + property initializer (from C# to F#)

查看:95
本文介绍了对象初始值设定项+属性初始值设定项(从C#到F#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Person,我想使用属性初始值设定项来初始化Name,并使用构造函数来初始化Age.

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

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

推荐答案

应该简单

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

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

这篇关于对象初始值设定项+属性初始值设定项(从C#到F#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆