Ben*_*sen 3 c# syntax f# object-construction
在 C# 中,可以用相当简洁的语法构造对象树:
var button = new Button() { Content = "Foo" };
Run Code Online (Sandbox Code Playgroud)
在 F# 中是否有一种惯用的方法来执行类似的操作?
记录有很好的语法:
let button = { Content = "Foo" }
Run Code Online (Sandbox Code Playgroud)
据我所知,对象构造似乎是另一回事。通常我会编写如下代码:
let button = new Button()
button.Content <- "Foo"
Run Code Online (Sandbox Code Playgroud)
甚至:
let button =
let x = new Button()
x.Content <- "Foo"
x
Run Code Online (Sandbox Code Playgroud)
解决该问题的一种方法是使用自定义的流畅组合运算符:
// Helper that makes fluent-style possible
let inline (.&) (value : 'T) (init: 'T -> unit) : 'T =
init value
value
let button = new Button() .& (fun x -> x.Content <- "Foo")
Run Code Online (Sandbox Code Playgroud)
是否有内置语法可以实现此目的 - 或者其他推荐的方法?
F# 允许您在构造函数调用中直接设置属性,所以我认为这应该适合您:
let button = Button(Content = "Foo")
Run Code Online (Sandbox Code Playgroud)