自 '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/