且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么 C# switch 语句不允许使用 typeof/GetType()?

更新时间:2023-11-09 21:33:10

问题是 switch(根据规范)仅适用于原语(int 等)和字符串.但是,是的,拥有 F# 样式匹配会很好.

从第 8.7.2 节开始:

开关标签:案例常量表达式:默认   :

...switch 语句的控制类型由 switch 表达式确定.如果 switch 表达式的类型是 sbyte, byte, short, ushort, int, uint, long,ulong、char、string 或 enum 类型,那么这是开关的控制类型陈述.否则,必须存在一个用户定义的隐式转换(第 6.4 节)将 switch 表达式的类型转换为以下可能的控制类型之一:sbyte,字节,短,ushort,int,uint,long,ulong,char,字符串.如果没有这样的隐含存在转换,或者如果存在多个这样的隐式转换,则编译时发生错误.

然而,很明显,使用这样一个受限集可以实现简单(高效)的 IL.请注意,string 是通过字典映射到整数来处理的.

As in this example:

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

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.