我有两个接口(interface):IStateIAction
一个状态有一个方法:GetActions——它返回一个 IActions 的集合。
Action 有一个方法: Apply - 它作用于一个状态,返回一个新的状态。

IState 接受一个类型参数来控制它通过 get 操作返回的操作类型,
IAction 接受一个类型参数来控制它可以作用于哪种状态。
(按排序,我看实现)。
我希望能够保证一个状态只返回可以作用于相同类型状态的 Action 。

type IAction<'S when 'S:>IState> =
    abstract member Apply : 'S->'S

and IState<'A when 'A:>IAction<'S when 'S:> typeof(this)>> =
    abstract member GetActions : seq<'A>

但显然 typeof(this) 不是一回事。
我怎样才能有一个类型约束来确保我的类型参数的类型等于我定义的类型?

最佳答案

首先避免陷入问题的解决方案

不是您问题的直接答案,但它应该可以解决您的原始问题:

type StateMachine<'State, 'Action> =
    interface
        abstract Apply : 'State * 'Action -> 'State
        abstract GetActions : 'State -> 'Action seq
    end

这种解决问题的方法受到 ML's module system 的启发

更丑陋的解决方案

如果你真的想要两个紧密耦合的接口(interface),你可以这样做:
type IState<'Action, 'State when 'Action :> IAction<'State, 'Action> and 'State :> IState<'Action, 'State>> =
    interface
        abstract GetActions : unit -> 'Action seq
    end

and IAction<'State, 'Action when 'Action :> IAction<'State, 'Action> and 'State :> IState<'Action, 'State>> =
    interface
        abstract Apply : 'State -> 'State
    end

// Some stupid types to illustrate how to implement the interfaces
type State() =
    interface IState<Action, State> with
        member this.GetActions() = Seq.empty

and Action() =
    interface IAction<State, Action> with
        member this.Apply s = s

我希望人们不要开始使用第二个解决方案,并用它来制作以我命名的设计模式:)

关于.net - 圆形类型约束,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10460310/

10-14 11:29
查看更多