如何正确使用 C# 8.0 switch case

Rox*_*Pro 3 c# error-handling exception switch-statement c#-8.0

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

这是我的代码:

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

但是我收到了以下消息:

错误 CS0201 只能将赋值、调用、递增、递减、等待和新对象表达式用作语句。

错误 CS0029 无法将类型“bool”隐式转换为“System.Exception”

Mar*_*ell 8

也许是这样的:

    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
       };
Run Code Online (Sandbox Code Playgroud)

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

UserNotFoundException unfe => $"User is not found: {unfe.UserName}",
Run Code Online (Sandbox Code Playgroud)