f#中具有属性赋值的多个构造函数

时间:2011-03-15 03:36:08

标签: f#

我希望有一个空白的构造函数和一个构造函数重载,它接受一个参数并将其分配给公共属性。

这是我被困的地方:

type TemplateService() = 
    interface ITemplateService with

        //Properties
        member TemplateDirectory = ""

        //Constructors
        new (templateDirectory:string) = //Error here.
            if (templateDirectory == null) then
                raise (new System.ArgumentNullException("templateDirectory"))
            TemplateDirectory = templateDirectory;

它给出了错误:对象表达式中的'意外关键字'new'。预期的“会员”,“覆盖”或其他令牌。

如果我使用member,则属性TemplateDirectory会出现此错误:

This instance member needs a parameter to represent the object being invoked. Make the member static or use the notation 'member x.Member(args) = ...'

3 个答案:

答案 0 :(得分:6)

你可以试试这个。

type TemplateService(templateDirectory : string) = 
    do
        if templateDirectory = null then nullArg "templateDirectory"

    new() = TemplateService("")

    interface ITemplateService with
        member this.TemplateDirectory = templateDirectory

答案 1 :(得分:0)

不幸的是,如果你想使用一个接口并将值传递给构造函数nyinyithann答案是正确的。您可以在这样的构造函数调用中设置公共属性。

type TemplateService() = 
    let mutable templateDirectory = ""

    member this.TemplateDirectory
        with get() = templateDirectory
        and set directory = 
            if directory = null then
                raise (new System.ArgumentNullException "templateDirectory")
            templateDirectory <- directory

let template = TemplateService(TemplateDirectory = "root")

现在,如果您想使用界面,这将无效。

type ITemplateService =
     abstract TemplateDirectory : string with get, set

type TemplateService() = 
    let mutable templateDirectory = ""

    interface ITemplateService with
        member this.TemplateDirectory
            with get() = templateDirectory
            and set directory = 
                if directory = null then
                    raise (new System.ArgumentNullException "templateDirectory")
                templateDirectory <- directory

let template = TemplateService(TemplateDirectory = "root") // error

你被迫使用这个丑陋的东西。

let template = TemplateService()
(template :> ITemplateService).TemplateDirectory <- "root"

答案 2 :(得分:0)

您将构造函数放在接口的定义中,这就是错误的原因。此外,您试图将值存储到仅获取属性,而应使用后备存储。

最后我会推荐nyinyithann的版本,因为它更符合通常的F#样式(最小变量),只是希望在你有用的情况下让版本更接近你的版本。

type TemplateService() = 
    let mutable directory = ""

    interface ITemplateService with

        //Properties
        member this.TemplateDirectory = directory

    //Constructors
    new (templateDirectory:string) =
        if (templateDirectory = null) then
            raise (new System.ArgumentNullException("templateDirectory"))
        directory <- templateDirectory;