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

后端 未结 10 2061
被撕碎了的回忆
被撕碎了的回忆 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:26

    I would add to Peter's excellent analysis the following thought:

    Fundamenatally, the purpose of a "switch" is to choose one of some number of distinct possibilities. A given value of enum, integer, Boolean or string type can only be one value, so it makes sense to "switch" on such a value. But types are fundamentally different. A given value usually has many types. Types frequently overlap. The proposed "type switch" does not match the stated purpose of the switch construct.

提交回复
热议问题