dev*_*ium 5 c# oop generics circular-dependency
我定义了以下接口:
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);
}
Run Code Online (Sandbox Code Playgroud)
基本上,IStateSpace界面应该类似于棋盘,并且在棋盘的每个位置上,您都有一组可能的动作。这里的那些动作被称为IActions。我以这种方式定义了这个接口,所以我可以适应不同的实现:然后我可以定义实现 2D 矩阵、3D 矩阵、图形等的具体类。
public interface IAction<State, Action> {
IStateSpace<State, Action> StateSpace { get; }
}
Run Code Online (Sandbox Code Playgroud)
一IAction,将向上移动(这是,如果在(2, 2)转会(2, 1)),向下移动,等等。现在,我会想,每个动作都有访问STATESPACE所以它可以做一些检查逻辑。这个实现是否正确?或者这是循环依赖的坏情况?如果是,如何以不同的方式实现“相同”?
谢谢
您指出的循环引用不是问题。为了编译您的代码,您需要修改您的IAction接口定义:
public interface IAction<State, Action>
where State : IState
where Action: IAction<State, Action>
{
IStateSpace<State, Action> StateSpace { get; }
}
Run Code Online (Sandbox Code Playgroud)
循环引用怎么样:)通常编译器会使用占位符来处理它们。在泛型类型约束的情况下,这可能甚至没有必要。一个小注意事项:如果您在不在同一程序集中的类之间定义循环引用,则会出现问题。