简体   繁体   English

C# - 类型检查接口

[英]C# - Type check an interface

I am building a StateMachine.我正在构建一个状态机。 For my States I use an interface:对于我的国家,我使用一个接口:

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

I always have a IState currentState active, I would like to check which type of State it is.我总是有一个IState currentState活动,我想检查它是哪种类型的状态。 Lets say I have WalkingState and RunningState , I would like to check which one is currently Active.可以说我有WalkingStateRunningState ,我想检查哪一个是当前活动。

I tried something like:我试过类似的东西:

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

But It does not allow me to cast currentState to a Type, and nothing else I've tried has worker either.但它不允许我将 currentState 转换为 Type,而且我尝试过的其他任何东西也没有工作人员。

This will work:这将起作用:

currentState.GetType() == typeof(T)

Edit:编辑:

As mentioned in Rajan Prasad's answer , you can use is .正如Rajan Prasad 的回答中提到,您可以使用is is and GetType() == typeof(T) behave differently. isGetType() == typeof(T)表现不同。 Primarily:主要是:

  • If A : B , instanceOfA is instanceOfB is true while instanceOfA.GetType() == typeof(B) is false .如果A : BinstanceOfA is instanceOfBtrueinstanceOfA.GetType() == typeof(B)false

If you have only 1 level of inheritance from IState (ie only FirstLevelState : IState , no SecondLevelState : FirstLevelState ) use is , it is more performant and has fewer edge cases.如果您从IState只有 1 个继承IState (即只有FirstLevelState : IState ,没有SecondLevelState : FirstLevelState ),则使用is ,它的性能更高并且边缘情况更少。 Otherwise, use GetType() == typeof(T) .否则,使用GetType() == typeof(T)

This question details type checking method differences: Type Checking: typeof, GetType, or is?这个问题详细说明了类型检查方法的区别: Type Checking: typeof, GetType, or is? . .

You should use something like this你应该使用这样的东西

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

Also you can use Type.IsAssignableFrom ().您也可以使用 Type.IsAssignableFrom ()。 He requires two instaces of System.Type, because you havent to have statically declared type.他需要 System.Type 的两个实例,因为您还没有静态声明类型。 It differents on the other parts your code, but you should know about it.它在您的代码的其他部分有所不同,但您应该了解它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM