Why doesn't C# switch statement allow using typeof/GetType()?

后端 未结 10 2051
被撕碎了的回忆
被撕碎了的回忆 2020-12-15 08:56

As in this example:

switch ( myObj.GetType ( ) )
{
    case typeof(MyObject):
        Console.WriteLine ( \"MyObject is here\" );
        break;
}

10条回答
  •  既然无缘
    2020-12-15 09:07

    In C# 7.0 you can do it. See Pattern Matching in C# 7.0 Case Blocks

    // ----- Assume that spaceItem is of type SpaceType,
    //       and that Planet and Star derive from SpaceType.
    switch (spaceItem)
    {
      case Planet p:
        if (p.Type != PlanetType.GasGiant)
          LandSpacecraft(p);
        break;
      case Star s:
        AvoidHeatSource(s);
        break;
      case null:
        // ----- If spaceItem is null, processing falls here,
        //       even if it is a Planet or Star null instance.
        break;
      default:
        // ----- Anything else that is not Planet, Star, or null.
        break;
    }
    

提交回复
热议问题