gpt4 book ai didi

c# - 如何正确使用C# 8.0 switch case

转载 作者:行者123 更新时间:2023-12-02 11:01:52 26 4
gpt4 key购买 nike

我尝试实现 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."
};

但我收到以下消息:

Error CS0201 Only assignment, call, increment, decrement, await, andnew 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}",

关于c# - 如何正确使用C# 8.0 switch case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59841116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com