代码之家  ›  专栏  ›  技术社区  ›  Roxy'Pro

如何正确使用C#8.0开关箱

  •  1
  • Roxy'Pro  · 技术社区  · 5 年前

    如果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."
       };
    

    但我想说一句话:

    仅限赋值、调用、递增、递减、等待和 新的对象表达式可以用作语句。

    '系统。异常'

    1 回复  |  直到 5 年前
        1
  •  6
  •   Marc Gravell    5 年前

    可能是这样的:

        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}",
    
    推荐文章