繁体   English   中英

F# - 调用方法并在构造函数中赋值给属性

[英]F# - call method and assign to property in constructor

在F#中,我试图编写一个具有构造函数的类,该构造函数调用方法并将返回的值赋给属性。 目前我无法编译。 这是我的F#代码:

namespace Model

type MyClass() = 
    do
        MyProperty <- GenerateString()

    member val public MyProperty = ""
        with get, set

    member public this.GenerateString() = 
        "this is a string"

编译错误是:FS0039未定义值或构造函数MyProperty。

我该怎么做才能解决这个问题?

我已经粘贴了一些C#代码来演示我正在尝试做的事情:

public class MyClass
{
    public string MyProperty { get; set; }

    public MyClass()
    {
        MyProperty = GenerateString();
    }

    private string GenerateString()
    {
        return "this is a string";
    }
}

您收到编译器错误,因为您需要定义对要在构造函数中使用的MyClass的当前实例的引用。 但是,即使您这样做,您也会发现代码在运行时失败:

type MyClass() as self = 
    do
        self.MyProperty <- self.GenerateString()

    member val public MyProperty = ""
        with get, set

    member public this.GenerateString() = 
        "this is a string"

这失败并出现错误System.InvalidOperationException: The initialization of an object or value resulted in an object or value being accessed recursively before it was fully initialized.

我建议在类中使用本地绑定来容纳属性值,而不是试图从构造函数内部改变类的属性。 像这样的东西:

type MyClass() as self = 

    let mutable value = ""
    do value <- self.GenerateString()

    member public this.MyProperty
        with get() = value
        and set (v) = value <- v

    member public this.GenerateString() = 
        "this is a string"

亚伦给出了一个很好的答案,但这里有一个替代方案:

type MyClass() = 
    let genString () = "this is a string"
    member val public MyProperty = genString() with get, set
    member public this.GenerateString = genString

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM