是否可以在switch语句中调用方法?

时间:2015-01-28 22:36:49

标签: c#

简单的问题。是否可以在C#中的switch语句中调用方法?要求.NET> = 4.5

var x = "Hello World";
switch(x)
{
    case "Foo":
        break;
    // What I actually want to do
    case x.StartsWith("Hello"):
        return "Bar";
}

1 个答案:

答案 0 :(得分:7)

没有。 case必须跟随编译时常量,方法调用肯定不是其中之一。

来自C#规范的C#语法的一部分:

switch-statement:
    switch   (   expression   )   switch-block

switch-block:
{   switch-sectionsopt   }

switch-sections:
    switch-section
    switch-sections   switch-section

switch-section:
    switch-labels   statement-list

switch-labels:
    switch-label
    switch-labels   switch-label

switch-label:
    case   constant-expression   :
    default   :

如您所见,case必须跟随 constant-expression ,其描述为

  

constant-expression 是一个可以完全评估的表达式   编译时。

相关问题