C#switch语句的限制 - 为什么? [英] C# switch statement limitations - why?

查看:147
本文介绍了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;
  }

下面的开关()语句失败,预计整型值'和语句失败,'恒定值预期'。

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语句这确实是使用跳转表一个恒定的时间分支。然而,在稀疏的案件所指出的伊万汉密尔顿编译器可能会产生一些其他类别。

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语句的限制 - 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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