C#为什么允许this:
var s = "Nice";
switch (s)
{
case "HI":
break;
const string x = "Nice";
case x:
Console.Write("Y");
break;
}
但不包括 this:
var s = "Nice";
switch (s)
{
const string x = "Nice";
case x:
Console.Write("Y");
break;
}
@rtuner
,case
语句需要在编译时确定常量,因为switch
的实现是一个字典,而不是一系列的if/else if
语句。它需要将它们转换为可以作为字典键的对象。同时,评估case
不能有任何副作用,因为这些副作用在测试case
时不会像在C++中那样生成。 - Servy