1

鉴于我有类型:

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

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

4

1 回答 1

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
于 2012-05-11T18:07:33.033 回答