簡體   English   中英

F# Object 樹語法

[英]F# Object Tree Syntax

在 C# 中,可以用相當簡潔的語法構造 object 樹:

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

在 F# 中是否有慣用的方法來做類似的事情?

記錄有很好的語法:

let button = { Content = "Foo" }

據我所知,Object 的構造似乎是另一回事。 通常我會編寫如下代碼:

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

甚至:

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

解決該問題的一種方法是使用自定義流式組合運算符:

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

是否有內置語法來實現這一點 - 或其他推薦的方法?

F# 允許您在構造函數調用中設置屬性,所以我認為這應該適合您:

let button = Button(Content = "Foo")

在 C# 中,這種漂亮的語法稱為object 初始化程序,然后可以刪除 ( () (1)。 要在初始化后更改 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")

在 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