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

Red*_*ign 3 methods f# constructor properties

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

namespace Model

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

    member val public MyProperty = ""
        with get, set

    member public this.GenerateString() = 
        "this is a string"
Run Code Online (Sandbox Code Playgroud)

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

我能做些什么来解决这个问题?

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

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

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

    private string GenerateString()
    {
        return "this is a string";
    }
}
Run Code Online (Sandbox Code Playgroud)

Aar*_*ach 6

您收到编译器错误,因为您需要定义对要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"
Run Code Online (Sandbox Code Playgroud)

这失败并出现错误 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"
Run Code Online (Sandbox Code Playgroud)