C#-类型检查接口

问题描述 投票:0回答:3

我正在建立一个StateMachine。对于我的国家,我使用界面:

public interface IState
{
    void Enter();
    void Execute();
    void Exit();
}

我一直有一个IState currentState处于活动状态,我想检查它是哪种状态。可以说我有WalkingStateRunningState,我想检查哪个当前处于活动状态。

我尝试过类似的事情:

public bool IsCurrentState<T>()
{
    return (Type)currentState == typeof(T);
}

但是它不允许我将currentState转换为Type,并且我尝试过的其他任何方法都没有worker。

c#
3个回答
2
投票

您应该使用类似这样的东西

public bool IsCurrentState<T>() {
    return currentState is T ;
}

2
投票

这将起作用:

currentState.GetType() == typeof(T)

编辑:

Rajan Prasad's answer中所述,您可以使用isisGetType() == typeof(T)的行为不同。主要:

  • 如果为A : B,则instanceOfA is instanceOfBtrue,而instanceOfA.GetType() == typeof(B)false

如果您从IState仅具有1个继承级别(即仅FirstLevelState : IState,没有SecondLevelState : FirstLevelState)使用is,则性能更高且边缘情况更少。否则,请使用GetType() == typeof(T)

此问题详细说明了类型检查方法的区别:Type Checking: typeof, GetType, or is?


0
投票

也可以使用Type.IsAssignableFrom()。他需要System.Type的两个实例,因为您没有静态声明的类型。它与您代码的其他部分有所不同,但是您应该了解它。

© www.soinside.com 2019 - 2024. All rights reserved.