我在F#中know that:
public class Person {
public DateTime BirthDate { get; set; }
public string Name { get; set; }
}
你可以像这样初始化它,这很好:
let p = new Person (Name = "John", BirthDate = DateTime.Now)
但是如果C#类也有这样的构造函数,你将如何在F#中初始化它:
public class Person {
public Person(int id)
{
Id = id
}
public int Id {get; private set;}
public DateTime BirthDate { get; set; }
public string Name { get; set; }
}
我们是否被迫使用这种结构?
let p = new Person (123)
p.Name <- "John"
p.BirthDate <- DateTime.Now
答案 0 :(得分:11)
对auto属性使用equivilent F#语法可能如下所示。您可以按如下方式组合构造函数和属性初始化:
type Person(id : int) =
member val Id = id with get,set
member val BirthDate = DateTime.MinValue with get,set
member val Name = "" with get,set
let p = Person(5, Name = "Stu")
p |> Dump
答案 1 :(得分:6)
System.UriBuilder
BCL类看起来像OP中的Person
类,所以我将以此为例:
> let ub = UriBuilder("http://blog.ploeh.dk", Path = "about");;
val ub : UriBuilder = http://blog.ploeh.dk:80/about