为什么 C# switch 语句不允许使用 typeof/GetType()? [英] Why doesn't C# switch statement allow using typeof/GetType()?

查看:24
本文介绍了为什么 C# switch 语句不允许使用 typeof/GetType()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如本例所示:

switch (myObj.GetType()){案例类型(MyObject):Console.WriteLine("MyObject 在这里");休息;}

解决方案

问题是 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.

这篇关于为什么 C# switch 语句不允许使用 typeof/GetType()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆