'Return this as inherited type
I am creating a finite state machine class, but am running into some trouble returning this as the correct type.
The parent class
public class FsmState<StateAsEnum, SelfClass> where StateAsEnum : Enum
{
protected SelfClass NextState;
public StateAsEnum StateName { get; protected set; }
public NpcState Process()
{
if (Stage == FsmStage.Enter) Enter();
if (Stage == FsmStage.Update) StateUpdate();
if (Stage == FsmStage.Exit)
{
Exit();
return NextState;
}
return this; //the trouble.
}
}
I can not ensure that SelfClass and the type FsmState are the same. When I inherit from this class I would like to return this as the inherited class.
class NpcState : FsmState<NpcState.States, NpcState>
{
Process();
}
This guy is used in
NpcState currentState
loop
{
currentState = currentState.Process();
}
Solution 1:[1]
Okay I figured it out. It doesn't look nice but the casting helped when I applied recursive inheritance on the types.
public class FsmState<StateAsEnum, SelfClass> where StateAsEnum : Enum where SelfClass : FsmState<StateAsEnum,SelfClass>
public SelfClass Process()
{
...
return (SelfClass) this;
}
It's not pretty but it works.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Just_Alex |
