我有两个接口(interface):IState
和 IAction
.
State 有一个方法:GetActions - 它返回 IActions 的集合。
一个 Action 有一个方法: Apply - 它作用于一个 State,返回一个新的 State。
IState 采用类型参数来控制它通过 get 操作返回的操作类型,
IAction 接受一个类型参数来控制它可以作用于哪种状态。
(按排序,我 ment 实现)。
我希望能够保证 State 只返回可以作用于同一类型状态的操作。
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/