F#如何处理这个递归的mutal类方法

时间:2015-10-08 08:46:29

标签: f#

我有以下代码,我需要在我自己的类上调用我通过相互类的引用引用(希望有意义,如果不是代码示例更好地解释它)。

不幸的是它确实有效,因为我在...之前得到了不确定类型对象的"查找..." ' x.Connections。[0] .Dest.Func'一部分。

任何人都可以想办法解决这个问题,可能我只想采用一种不同的方法吗?

type Node() =
    member x.Connections = new System.Collections.Generic.List<Connection>()
    member x.Connect other = x.Connections.Add(Connection(x, other))
    member x.Func i : unit = x.Connections.[0].Dest.Func i
and Connection(source : Node, dest : Node) =
    member val Source = source
    member val Dest = dest

忽略在Node上调用Func方法没有任何意义的事实,我已经从实际代码中简化了这一点,试图只显示导致问题的原因。 提前谢谢。

2 个答案:

答案 0 :(得分:3)

尝试在最后声明该方法:

type Node() =
    member x.Connections = new System.Collections.Generic.List<Connection>()
    member x.Connect other = x.Connections.Add(Connection(x, other))

and Connection(source : Node, dest : Node) =
    member val Source = source
    member val Dest = dest

type Node with
    member x.Func i : unit = x.Connections.[0].Dest.Func i

或者可能更好地交换类型的顺序:

type Connection(source : Node, dest : Node) =
    member val Source = source
    member val Dest = dest
and Node() =
    member x.Connections = new System.Collections.Generic.List<Connection>()
    member x.Connect other = x.Connections.Add(Connection(x, other))
    member x.Func i : unit = x.Connections.[0].Dest.Func i

答案 1 :(得分:3)

您还可以向Dest添加类型注释,它似乎是将类型推理算法抛出到循环中的关键符号:

type Node() =
    member x.Connections = new System.Collections.Generic.List<Connection>()
    member x.Connect other = x.Connections.Add(Connection(x, other))    
    member x.Func i : unit = x.Connections.[0].Dest.Func i                             
and Connection(source : Node, dest : Node) =
    member val Source = source
    member val Dest : Node = dest