如何正确使用 C# 8.0 switch case

How to properly use C# 8.0 switch case

我已经尝试实现 c# 8.0 switch-case,但不幸的是它没有工作, 我想如果 case 满足 return switch 表达式中那个满足的 case 的特定字符串。

这是我的代码:

public static void GetErrMsg(Exception ex) =>
   ex switch
   {
       ex is UserNotFoundException => "User is not found.",
       ex is NotAuthorizedException => "You'r not authorized."
   };

但我收到以下消息:

Error CS0201 Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement.

Error CS0029 Cannot implicitly convert type 'bool' to 'System.Exception'

可能是这样的:

    public static string GetErrMsg(Exception ex) =>
       ex switch
       {
           UserNotFoundException _ => "User is not found.",
           NotAuthorizedException _ => "You'r[e] not authorized.",
           _ => ex.Message, // or something; "Unknown error" perhaps
       };

这里的_是弃牌;如果你真的想使用检测到的类型中的其他东西,你可以命名它,例如:

UserNotFoundException unfe => $"User is not found: {unfe.UserName}",