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

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

As in this example:

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

10条回答
  •  -上瘾入骨i
    2020-12-15 09:12

    The problem is that switch (per the spec) only works with primitives (int etc) and strings. But yes, it would be nice to have F#-style matching.

    From §8.7.2:

    switch-label:
       case   constant-expression   :
       default   :
    

    ... The governing type of a switch statement is established by the switch expression. If the type of the switch expression is sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or an enum-type, then that is the governing type of the switch statement. Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the type of the switch expression to one of the following possible governing types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string. If no such implicit conversion exists, or if more than one such implicit conversion exists, a compile-time error occurs.

    It is obvious, however, that working with such a restricted set allows for simple (and efficient) IL. Note that string is handled via a dictionary map to an integer.

提交回复
热议问题