我目前面臨的一個非常令人不安的問題:泛型與約束的層次
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
將作爲矩陣作爲圖實現,等等)。
我能脫身嗎?你通常如何解決這類問題?在這些情況下使用哪種設計?
感謝