5

我定义了以下接口:

public interface IStateSpace<State, Action>
where State : IState
where Action : IAction<State, Action> // <-- this is the line that bothers me
{
    void SetValueAt(State state, Action action);
    Action GetValueAt(State state);
}

基本上,IStateSpace界面应该类似于棋盘,并且在棋盘的每个位置上,您都有一组可能的动作要做。这里的那些动作被称为IActions。我以这种方式定义了这个接口,因此我可以适应不同的实现:然后我可以定义实现 2D 矩阵、3D 矩阵、图形等的具体类。

public interface IAction<State, Action> {
    IStateSpace<State, Action> StateSpace { get; }
}

一个IAction, 将向上移动(如果(2, 2)移动到(2, 1)),向下移动等。现在,我希望每个操作都可以访问 StateSpace,以便它可以执行一些检查逻辑。这个实现正确吗?或者这是循环依赖的坏情况?如果是,如何以不同的方式完成“相同”?

谢谢

4

1 回答 1

2

您指出的循环引用不是问题。要编译您的代码,您需要修改IAction接口定义:

public interface IAction<State, Action>
    where State : IState
    where Action: IAction<State, Action>
{
    IStateSpace<State, Action> StateSpace { get; }
}

循环引用怎么样 :) 通常编译器会使用占位符来处理它们。在泛型类型约束的情况下,这可能甚至没有必要。一个小提示:如果您在不在同一个程序集中的类之间定义循环引用,这将成为一个问题。

于 2010-05-20T22:15:53.313 回答