管道记录到对象参数列表

时间:2012-05-11 17:53:29

标签: f#

鉴于我有类型:

type NewsMessage(identifier:string, headline:string)

和此记录:

type NewsMessageParams = { 
    identifier:string
    headline:string 
}

是否有隐式方法使记录适应类构造函数?

像这样:

let newsMessageParmas = {identifier=""; headline=""}
new NewsMessage(newsMessageParams) //this is where i need help

您可以使用||>语法对元组执行此操作。我想用记录来做这件事。

1 个答案:

答案 0 :(得分:3)

这样的事情会起作用:

let toClass {identifier = i; headline = h} = NewsMessage(i, h)

// Usage
let newsMessageParams = {identifier = ""; headline = ""}
let newsMessage = newsMessageParams |> toClass

请注意,对象构造函数在F#中不是第一类,因此如果将NewsMessage声明为有区别的联合,则您有更多机会使用管道运算符:

type NewsMessage = NewsMessage of string * string
let toTuple {identifier = i; headline = h} = i, h

let newsMessageParams = {identifier = ""; headline = ""}
let newsMessage = newsMessageParams |> toTuple |> NewsMessage