可以从 C# 中的 switch case 分配返回值吗?

Phi*_*yan 0 c# switch-statement

我见过的所有 C# switch 语句的例子如下

var variable, result; 

switch (variable) {
 case 1: result = somevalue; break;
 case 2: result = someothervalue; break;
}
Run Code Online (Sandbox Code Playgroud)

但是,我想要类似的东西

var result = switch (variable) {
   case 1: return <somevalue>;
   case 2: return <someothervalue>;
  }
Run Code Online (Sandbox Code Playgroud)

可能的?(也许我需要break在箱子里,但这是一个回报......)

pro*_*mab 7

在 c# 8.0 中,您可以使用新的 switch 语法:

var area = figure switch 
{
    Line _      => 0,
    Rectangle r => r.Width * r.Height,
    Circle c when c.Radius == 0 => throw new ThrowSomeException(c),
    Circle c    => Math.PI * c.Radius * c.Radius,
    _           => throw new UnknownFigureException(figure)
};
Run Code Online (Sandbox Code Playgroud)

您可以在此处阅读有关新功能的更多信息。


MFa*_*MAR 5

背后的基本思想return <somevalue>是正确的,但它switch是一个控制语句,所以它没有return价值。你必须使它成为这样的方法:

dynamic SomeMethod(int variable)
{
   switch(variable)
   {
       case 1: return "text";
       case 2: return 5;

       // Or manually return something out of switch scope
       // because the method has to return something
       default: return null;
   }
}

void Test()
{
    // Now you have a value assigned to an variable
    // that comes from SomeMethod
    // which is generated (selected) by switch
    var result1 = SomeMethod(1); // string
    var result2 = SomeMethod(2); // int
    var result3 = SomeMethod(123); // null
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下我还需要解释一下:方法不能return 隐式类型(var),因为编译器无法猜测return 类型是什么。但是你可以return 动态的,现在类型会在运行时改变。你也不能使用dynamicinswitch因为它需要一个空的类型。

如果您希望它简短(在方法中),可以使用 lambda 创建一个匿名方法:)

var result =
    (Func<int, dynamic>)
    ( (x) =>
    {
        switch(x)
        {
            case 1: return "text";
            case 2: return 5;
            default: return null;
        }
    } // Lambda
    ) // Func<int, dynamic> (takes int parameters, returns dynamic value)
    (); // Call it and get return value to assign
Run Code Online (Sandbox Code Playgroud)

但是,我强烈建议您阅读一些文章,例如语句方法类型……