Why doesn#39;t C# switch statement allow using typeof/GetType()?(为什么 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()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 C# switch 语句不允许使用 typeof/GetType()?


- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01