我最近发现(见this page末尾附近)可以在初始化时设置属性,如下面的最后一行所示。这非常简洁:
type Account() =
let mutable balance = 0.0
member this.Balance
with get() = balance
and set(value) = balance <- value
let account1 = new Account(Balance = 1543.33)
有没有办法以类似简洁的方式设置子属性(即属性的属性),而不会完全覆盖它们?
例如,我想写下这些内容:
type Person() =
let mutable name = ""
let mutable someProperty = ""
member this.Name
with get() = name
and set(value) = name <- value
member this.SomeProperty
with get() = someProperty
and set(value) = someProperty <- value
type Account() =
let mutable balance = 0.0
let mutable person = new Person(SomeProperty = "created by an account")
member this.Person
with get() = person
and set(value) = person <- value
member this.Balance
with get() = balance
and set(value) = balance <- value
let account1 = new Account(Balance = 1543.33, Person.Name = "John Smith")
但是,最后一行产生的编译错误并不完全合理:Named arguments must appear after all other arguments
。
请注意,这实际上是与C#库互操作,所以我不一定要为该属性构造一个新对象。如果可能的话,我不会在F#中使用这样的可变属性。
答案 0 :(得分:3)
是的,你可以这样做。
尝试以下方法:
let account1 = new Account(Balance = 1543.33, Person = Person(Name = "John Smith"))
修改海报后的修改问题: 如果我正确遵循,我仍然不能100%确定,但解决方案可能如下。它感觉不是特别有用,但鉴于这是为了与C#类交互,我不认为这是一个问题:
type Account() =
let mutable balance = 0.0
static let mutable person = new Person(SomeProperty = "created by an account")
member this.Person
with get() = person
and set(value) = person <- value
member this.Balance
with get() = balance
and set(value) = balance <- value
static member GetPerson = person
let account2 = new Account(Balance = 1543.33, Person = Person (Name = "John Smith", SomeProperty = Account.GetPerson.SomeProperty))