[英]override enum in derived class in C#
I'm creating an abstract
finite machine state class with an enum
for the possible commands it can receive, something like:我正在创建一个
abstract
有限机器状态类,其中包含它可以接收的可能命令的enum
,例如:
public abstract class FSMBase
{
public enum Commands {};
public enum States;
public Dictionary<Transition, States> AvailableTransitions;
public States CurrentState;
public abstract void InitCommandsAndStatesAndTransitiosnAndInitialState();
public void ProcessCommand(Commands _command)
{
Transition RequestedTransition = new Transition(CurrentState, command);
if(AvailableTransitions.TryGetValue(RequestedTransition, out State nextState) //pseudocode
{
CurrentState = nextState;
}
}
}
Then in the derived class I would like to override the States
, the Transitions
and the Commands
.然后在派生类中,我想覆盖
States
中, Transitions
和Commands
。 Something like:就像是:
public class MyFSM : FSMBase
{
public override void InitCommandsAndStatesAndTransitiosnAndInitialState()
{
States = {Off, starting, started, ...} //HERE IS MY PROBLEM
Commands = {start, stop, finish, ...}; // HERE IS MY PROBLEM
Transitions = new Dictionary<Transition, BaseState>
{
{new Transition(States.Off, Commands.Start), States.starting},
....
}
CurrentState = States.Off;
}
}
How do I override the enum
s in my derived class ???如何覆盖派生类中的
enum
???
Well, enum
is in fact int
( byte
, short
, long
ect.) and can't be overriden.好吧,
enum
实际上是int
( byte
、 short
、 long
等)并且不能被覆盖。 I suggest using generics instead我建议改用泛型
public abstract class FSMBase<State, Command>
where State : Enum // : Enum wants C# 7.3+
where Command : Enum {
//TODO: I suggest have these fields private, or at least, protected
public Dictionary<Transition, State> AvailableTransitions;
public State CurrentState;
public void ProcessCommand(Command _command) {
...
}
}
When implementing MyFSM
you can put required enums:在实现
MyFSM
您可以放置所需的枚举:
public class MyFSM : FSMBase<MyStates, MyCommands> {
...
}
Edit: in case of lower c# versions you can try same idea but different constraints:编辑:在较低的c# 版本的情况下,您可以尝试相同的想法但不同的约束:
public abstract class FSMBase<State, Command>
where State : struct
where Command : struct {
public State CurrentState;
...
// Instead of compile time error we are going to have runtime one,
// if either State or Command is not enum
static FSMBase() {
if (!typeof(State).IsEnum)
throw new InvalidCastException("Generic pararameter State must be enum!");
else if (!typeof(Command).IsEnum)
throw new InvalidCastException("Generic pararameter Command must be enum!");
}
}
...
public class MyFSM : FSMBase<MyStates, MyCommands> {
public override void InitCommandsAndStatesAndTransitiosnAndInitialState() {
...
CurrentState = MyStates.Off;
...
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.