我有一个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
答案 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")