C# switch statement limitations - why?(C# switch 语句限制 - 为什么?)
问题描述
在编写 switch 语句时,在 case 语句中可以打开的内容似乎有两个限制.
When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.
例如(是的,我知道,如果您正在做这种事情,这可能意味着您的 面向对象 (OO) 架构是不确定的——这只是一个人为的例子!),
For example (and yes, I know, if you're doing this sort of thing it probably means your object-oriented (OO) architecture is iffy - this is just a contrived example!),
Type t = typeof(int);
switch (t) {
case typeof(int):
Console.WriteLine("int!");
break;
case typeof(string):
Console.WriteLine("string!");
break;
default:
Console.WriteLine("unknown!");
break;
}
这里 switch() 语句失败并出现预期的整数类型的值",而 case 语句失败并出现预期的常量值".
Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.
为什么要设置这些限制,根本原因是什么?我看不出为什么 switch 语句 必须 只能屈服于静态分析,以及为什么要打开的值必须是整数(即原始值).理由是什么?
Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement has to succumb to static analysis only, and why the value being switched on has to be integral (that is, primitive). What is the justification?
推荐答案
这是我的原创帖子,引发了一些争论...... 因为它是错误的:
This is my original post, which sparked some debate... because it is wrong:
switch语句不一样作为一个大的 if-else 语句.每个案例都必须是唯一的并经过评估静态的.switch 语句确实一个恒定的时间分支,无论你有多少案例.if-else语句评估每个条件直到找到一个正确的.
The switch statement is not the same thing as a big if-else statement. Each case must be unique and evaluated statically. The switch statement does a constant time branch regardless of how many cases you have. The if-else statement evaluates each condition until it finds one that is true.
<小时>
事实上,C# switch 语句并不总是一个恒定时间的分支.
In fact, the C# switch statement is not always a constant time branch.
在某些情况下,编译器会使用 CIL switch 语句,这确实是使用跳转表的恒定时间分支.但是,在 Ivan Hamilton 指出的稀疏情况下,编译器可能会生成一些东西完全不同.
In some cases the compiler will use a CIL switch statement which is indeed a constant time branch using a jump table. However, in sparse cases as pointed out by Ivan Hamilton the compiler may generate something else entirely.
这实际上很容易通过编写各种 C# switch 语句来验证,有些稀疏,有些密集,并使用 ildasm.exe 工具查看生成的 CIL.
This is actually quite easy to verify by writing various C# switch statements, some sparse, some dense, and looking at the resulting CIL with the ildasm.exe tool.
这篇关于C# switch 语句限制 - 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# switch 语句限制 - 为什么?


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