简体   繁体   English

GetType和typeof

[英]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. 我正在使用Head First Design Patterns第10章中的gumballMachine应用程序。 full code here This works. 完整代码在这里

Problem: typeThing above smells! 问题:类型上面有气味! Is there a better way? 有没有更好的办法?

You could use the is operator : 您可以使用is运算符

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

This of course would result in true for all types that inherit from NoQuarterState as well though. 当然,这对于所有继承自NoQuarterState类型都NoQuarterState true 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: 如果可以修改GumballMachine类,则可以使用枚举代替类型:

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) {...}

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

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