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

boo*_*oop 0 c#

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

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

Mar*_*zek 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   :
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,case必须遵循constant-expression,这被描述为

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