简体   繁体   中英

GetType and typeof

Type typeThing = gumballMachine.GetState().GetType();
if (typeThing == typeof(NoQuarterState)) { ... }


IState state;
public IState GetState() {
    return state;
}


public class NoQuarterState : IState { ... }

I'm using a gumballMachine app from Ch10 of Head First Design Patterns. full code here This works.

Problem: typeThing above smells! Is there a better way?

You could use the is operator :

if(gumballMachine.GetState() is NoQuarterState)
{
   //..
}

This of course would result in true for all types that inherit from NoQuarterState as well though. Based on your example this shouldn't be a problem.

The question is why do you have to distinguish by type in the first place? Usually that's a sign that a better design is in order, ie maybe the the strategy pattern or another use of polymorphism could help.

If you can modify the GumballMachine class you could use an enum instead of types:

public enum StateEnum
{
   NoQuarterState,
   SomeOtherState
}

StateEnum GetState { get; }

if(gumballMachine.GetState.Equals(StateEnum.NoQuarterState)) { ... }

You can try

  object typeThing = gumballMachine.GetState();
  //1st way
  if (typeThing is NoQuarterState) {...}
  //Or 2nd way
  if ((typeThing as NoQuarterState)!=null) {...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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