我正在建立一个StateMachine。对于我的国家,我使用界面:
public interface IState
{
void Enter();
void Execute();
void Exit();
}
我一直有一个IState currentState
处于活动状态,我想检查它是哪种状态。可以说我有WalkingState
和RunningState
,我想检查哪个当前处于活动状态。
我尝试过类似的事情:
public bool IsCurrentState<T>()
{
return (Type)currentState == typeof(T);
}
但是它不允许我将currentState转换为Type,并且我尝试过的其他任何方法都没有worker。
您应该使用类似这样的东西
public bool IsCurrentState<T>() {
return currentState is T ;
}
这将起作用:
currentState.GetType() == typeof(T)
编辑:
如Rajan Prasad's answer中所述,您可以使用is
。 is
和GetType() == typeof(T)
的行为不同。主要:
A : B
,则instanceOfA is instanceOfB
为true
,而instanceOfA.GetType() == typeof(B)
为false
。如果您从IState
仅具有1个继承级别(即仅FirstLevelState : IState
,没有SecondLevelState : FirstLevelState
)使用is
,则性能更高且边缘情况更少。否则,请使用GetType() == typeof(T)
。
此问题详细说明了类型检查方法的区别:Type Checking: typeof, GetType, or is?。
也可以使用Type.IsAssignableFrom()。他需要System.Type的两个实例,因为您没有静态声明的类型。它与您代码的其他部分有所不同,但是您应该了解它。