我需要在另一个子类SubClass中引用接口IState的特定AIState,该子类使用与IState中的泛型类型相同的接口类.我很难正确地分析。
我正在构建一个Statemachine,它基于上下文工作:意味着每个状态+ SM只存在一次,使用SM的人只会调用类中的函数,并将上下文作为参数。上下文引用
我有接口
public interface IStateContext
{
IState<IStateContext> CurrentState { get; }
}
Interface IState <T> where T:IStateContext {
Execute(T context);
}我使用颜色实现了AI行为的状态可视化:
public class AIState : IState <AIContext> {
Color stateColor;
Execute(AIState) { //behavior}
}好的。现在问题开始了。我只能创建这样一个AIContext:
[System.Serializable]
public class AIContext : IStateContext
{
public AI ai;
public Animator animator;
public NavMeshAgent agent;
private IState<IStateContext> activeState;
public IState<IStateContext> ActiveState
{
get => activeState;
set => activeState = value;
}
}我需要活动状态是一个AIState,它只是不允许子类.我想要能够访问(AIContext) context.ActiveState.color!但只要它只是一个IState,它就没有“颜色”的信息。
尝试&错误1:我无法解析它。只是不让我这么做。
尝试&错误2:我不能在IStateContext中使用泛型类型,即IState,因为它只是泛型类型声明的循环……AIState : IState<AIContext<AIState<AI .....>>>
恐怕是结构性问题?我希望有人能看到。
编辑:问题不只是颜色,我可能希望稍后实现其他变量。这是解析。我的StateMAchine只使用泛化(IState -> Executes with IStateContext)。我只是看不到一个选项,可以将当前的活动状态保持在上下文中。
IStateContext有一个IState CurrentState,其中T:IStateContext,而在AIState中,我需要一个AIContext CurrentState。我就是不能解析它!
发布于 2020-05-08 17:08:07
方法A
如果您可以强制实现IState接口的任何类都有一个StateColor,那么只需向接口添加一个属性StateColor即可。
public interface IState<T> where T : IStateContext
{
Color StateColor { get; set; }
void Execute(T context);
}
public class AIState : IState<AIContext>
{
public Color StateColor { get; set; }
public void Execute(AIContext context) { }
}
[Serializable]
public class AIContext : IStateContext
{
private IState<IStateContext> activeState;
public IState<IStateContext> ActiveState
{
get => activeState;
set => activeState = value;
}
public IState<IStateContext> CurrentState => throw new NotImplementedException();
}这将允许您访问您的StateColor的AIContext的属性ActiveState。
var aiContext = new AIContext();
var stateColor = aiContext.ActiveState.StateColor;方法B
如果您不想修改IState接口,另一个选项可以是创建一个新接口,例如实现IState接口的IAIState。
public interface IAIState<T> : IState<T> where T : IStateContext
{
Color StateColor { get; set; }
}
public interface IState<T> where T : IStateContext
{
void Execute(T context);
}然后只需将activeState字段和ActiveState属性的类型更改为IAIState .
[Serializable]
public class AIContext : IStateContext
{
private IAIState<IStateContext> activeState;
public IAIState<IStateContext> ActiveState
{
get => activeState;
set => activeState = value;
}
IState<IStateContext> IStateContext.CurrentState { get; }
}..。要访问StateColor of ActiveState,如上文所述:
var aiContext = new AIContext();
var stateColor = aiContext.ActiveState.StateColor;https://stackoverflow.com/questions/61683989
复制相似问题