.net - 圆形类型约束

标签 .net generics f#

我有两个接口(interface):IStateIAction .
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/

相关文章:

types - 定义具有一定数量元素的数组类型

c# - .NET - 使用基于表单的身份验证在 (Domino) 服务器上使用 HTTP 服务

.net - 使用 Rx 求和

c# - 表单例份验证不适用于特定页面

Java泛型问题

Java 泛型,一种强制执行父类(super class)型或子类型的方法

f# - 打印到控制台并处理数组

.net - 从 Internet Explorer 访问硬件

Java 多态泛型调用

f# - F# 中的捕获计数