简体   繁体   English

F# Object 树语法

[英]F# Object Tree Syntax

In C# it is possible to construct object trees in a rather succint syntax:在 C# 中,可以用相当简洁的语法构造 object 树:

var button = new Button() { Content = "Foo" };

Is there an idiomatic way to do something similar in F#?在 F# 中是否有惯用的方法来做类似的事情?

Records have nice syntax:记录有很好的语法:

let button = { Content = "Foo" }

Object construction would appear to be a different matter, as far as I can tell.据我所知,Object 的构造似乎是另一回事。 Normally I would write code such as:通常我会编写如下代码:

let button = new Button()
button.Content <- "Foo"

Or even:甚至:

let button =
    let x = new Button()
    x.Content <- "Foo"
    x

One way to solve the problem is to use a custom fluent composition operator:解决该问题的一种方法是使用自定义流式组合运算符:

// 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")

Is there built-in syntax to achieve this - or another recommended approach?是否有内置语法来实现这一点 - 或其他推荐的方法?

F# lets you set properties right in the constructor call , so I think this should work for you: F# 允许您在构造函数调用中设置属性,所以我认为这应该适合您:

let button = Button(Content = "Foo")

In C#, this nice syntax is called object initializer and then the () can be removed (1).在 C# 中,这种漂亮的语法称为object 初始化程序,然后可以删除 ( () (1)。 To change an object "inline" (fluent style) after its initialization, I like to have a With() extension method similar to your .& operator (2):要在初始化后更改 object “内联” (流利风格) ,我喜欢使用类似于您的.&运算符(2)的With()扩展方法:

var button = new Button { Content = "Foo" }; // (1)

// (2)
public static T With<T>(this T @this, Action<T> update)
{
    change(@this);
    return @this;
}

var button2 = button.With(x => x.Content = "Bar")

In F#, for those who prefer piping instead of operator, the function can be named tap (see RxJs ) or tee (by Scott Wlaschin here ):在 F# 中,对于那些喜欢管道而不是操作员的人,function 可以命名为tap (见RxJs )或tee (由 Scott Wlaschin 在这里):

// f: ('a -> 'b) -> x: 'a -> 'a
let inline tee f x =
    f x |> ignore
    x

let button =
    Button(Content = "Foo")
    |> tee (fun x -> x.Color <- Blue)
    |> tee (fun x -> x.Content <- "Bar")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM