【发布时间】:2010-05-22 01:08:25
【问题描述】:
我目前面临一个非常令人不安的问题:
interface IStateSpace<Position, Value>
where Position : IPosition // <-- Problem starts here
where Value : IValue // <-- and here as I don't
{ // know how to get away this
// circular dependency!
// Notice how I should be
// defining generics parameters
// here but I can't!
Value GetStateAt(Position position);
void SetStateAt(Position position, State state);
}
正如您将在这里看到的,IPosition、IValue 和 IState 相互依赖。我该怎么办?我想不出任何其他设计可以绕过这种循环依赖,并且仍然准确地描述了我想要做的事情!
interface IState<StateSpace, Value>
where StateSpace : IStateSpace //problem
where Value : IValue //problem
{
StateSpace StateSpace { get; };
Value Value { get; set; }
}
interface IPosition
{
}
interface IValue<State>
where State : IState { //here we have the problem again
State State { get; }
}
基本上我有一个状态空间IStateSpace,里面有状态IState。它们在状态空间中的位置由IPosition 给出。然后每个状态都有一个(或多个)值IValue。我正在简化层次结构,因为它比描述的要复杂一些。使用泛型定义此层次结构的想法是允许相同概念的不同实现(IStateSpace 将被实现为矩阵和图等)。
我能逃脱惩罚吗?您一般如何解决此类问题?在这些情况下使用哪种设计?
谢谢
【问题讨论】:
标签: c# generics oop circular-dependency