c# - 为什么 C# switch 语句不能接受 'dynamic' 类型?

标签 c# dynamic switch-statement

'At compile time, an element that is typed as dynamic is assumed to support any operation' ,我认为这意味着如果我在 switch 语句中使用它,编译器会假定动态变量是 switch 语句支持的类型。

与我的想法相反,声明

dynamic thing = "thing";
switch (thing) {
   case "thing": {
      Console.WriteLine("Was a thing.");
      Console.ReadKey();
      break;
   }
   default: {
      Console.WriteLine("Was not thing.");
      Console.ReadKey();
      break;
   }
}

给出编译时错误:switch 表达式或 case 标签必须是 bool、char、string、integral、enum 或相应的可空类型。那么给出了什么?这种限制的原因是什么?

最佳答案

因为 case-labels 中使用的常量必须是与管理类型兼容的编译时常量。

在编译时您无法确定 dynamic 变量。

作为动态变量,您如何知道您将比较哪个值?case-label 可以包含任何类型的值。

看看这个

dynamic thing = "thing";
//and some later time `thing` changed to
thing = 1;

现在考虑一下您的 case-label(您将比较哪种类型的值)

关于c# - 为什么 C# switch 语句不能接受 'dynamic' 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21147841/

相关文章:

reactjs - 单击按钮动态加载 SCSS 文件

python - 使用 Pyparsing 根据 header 字段解析 CSV 数据

javascript - 如何在AG-Grid中设置列的动态字段?

swift - 为什么此 Switch 语句需要 'Switch Value' 和 'Compound case' 的括号?

c# - 从位图中删除一种颜色的所有色调

c# - WCF 服务不会返回 500 Internal Server Error。相反,只有 400 Bad Request

ios - UISegmentedControl 与 UICollectionView 错误与 Switch 语句

java - bindView switch-case 性能问题

c# - 在FTP服务器(PASV)上使用RETR时如何确定文件结尾

c# - 如何在 C#/.NET 中找到本地计算机的 FQDN?