我试图将我很久以前编写的C#应用程序重写为F#,但是遇到了一些麻烦,因为这是我第一次尝试在F#中编写有意义的东西。
在我的C#软件中,我有以下类“ Buildings”,这是我在应用程序的其余部分中需要使用的父类:
public class Buildings()
{
Buildings()
{
Spectre = new Spectres(this);
}
public double Height;
}
另一个称为“ Spectres”的类,仅在建筑物中使用:
public class Spectres(Buildings prntBuilding)
{
Spectres()
{
_prntBuilding = prntBuilding;
}
private Buildings _prntBuilding;
public double doSomethingToheight()
{
return _prntBuilding.Height * 2.0;
}
}
我的问题是:我该如何在F#中执行此操作,F#中是否有此父子关系的替代方法?
编辑:我找到了解决方案
type Buildings() as self =
member this.Hn = 1.0 with get, set
member val Spectre = new Spectres(self) with get, set
and Spectres(prntBuinding : Buildings) =
let DoSomethingToHeight = prntBuilding.Hn * 2.0
最佳答案
大概您的问题是由F#中的声明顺序影响第二种类型的可见性引起的。 (订单在F#中很重要。)
您可以使用相互递归的类型,而无需太多的hoopla来解决此问题,如下所示:
type Buildings() =
member val Height = 0.0 with get, set
and Spectres(prntBuilding : Buildings) =
member __.DoSomething () = prntBuilding.Height * 2.0
and
表示他们彼此了解。相互递归类型的文档在这里:https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/classes#mutually-recursive-types