在 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:对象或值的初始化导致对象或值在完全初始化之前被递归访问。
我建议在类内部使用本地绑定(bind)来容纳属性值,而不是尝试从构造函数内部改变类的属性。像这样的事情:
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"
关于methods - F# - 调用方法并分配给构造函数中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52005828/