编写带参数化构造函数的f#函数

时间:2014-05-17 21:10:17

标签: f#

我想编写一个从数据流创建对象的函数,例如

let nxL<'T  when 'T : (new : unit -> 'T)> (sr:StreamReader) = 
    let line = sr.ReadLine()
    if line <> null then 
        Some(new 'T(line))
    else
        None

然而,这不起作用,因为它失败了:

Calls to object constructors on typed parameters cannot be given arguments.

由于构造函数是一个函数而F#是一种函数式语言,这对我来说毫无意义。有谁知道如何创建一个将类型作为参数并返回新实例的函数?

2 个答案:

答案 0 :(得分:2)

虽然像@scrwtp建议的那样传递一个函数是一个很好的方法,但你想要的 是可能的:

let inline nxL (sr:StreamReader) = 
    let line = sr.ReadLine()
    if line <> null then 
        Some(^a : (new : string -> ^a) line)
    else
        None

答案 1 :(得分:0)

您可以使用Activator.CreateInstance创建一个给定类型的对象,但我并不认为您发布的代码段是必须的。不会传递一个带有字符串并返回所需类型对象的常规函数​​吗?如果你在意,可以选择工厂功能。像这样:

let nxL<'T> (cons: string -> 'T) (sr:StreamReader) : 'T option = 
    let line = sr.ReadLine()
    if line <> null then 
        Some (cons line)
    else
        None

除此之外,除了StreamReader之外,您实际上可以删除其上的所有类型注释,并且它将被推断为通用的(将它们保留在其上,以便清除代码段中的内容)

相关问题