为什么在循环复杂性中计算出Aren的开关表达式?

发布于 2025-02-10 05:42:21 字数 622 浏览 2 评论 0原文

假设我有这样的方法:

void DoStuff(int a)
{
    int b;
    switch (a)
    {
        case 1: 
            b = 5;
            break;
        case 2:
            b = 100;
            break;
        default:
            b = 0;
            break;
    }
    Console.WriteLine(b);
}

Visual Studio给出了4个循环复杂性(在我看来,实际的循环复杂性为3,但这是点)。

现在,如果我使用开关表达式重构代码,我会得到这样的:

void DoStuff(int a)
{
    int b = a switch
    {
        1 => 5,
        2 => 100,
        _ => 0
    };
    Console.WriteLine(b);
}

Visual Studio现在说循环复杂性是1,即使代码做完全相同的事情。循环复杂性实际上是否降低了?如果是这样,怎么样?

Let's say I have this method:

void DoStuff(int a)
{
    int b;
    switch (a)
    {
        case 1: 
            b = 5;
            break;
        case 2:
            b = 100;
            break;
        default:
            b = 0;
            break;
    }
    Console.WriteLine(b);
}

Visual studio gives a cyclomatic complexity of 4 (seems to me that the actual cyclomatic complexity is 3 but that is beside the point).

Now if I refactor the code using a switch expression I get this:

void DoStuff(int a)
{
    int b = a switch
    {
        1 => 5,
        2 => 100,
        _ => 0
    };
    Console.WriteLine(b);
}

Visual studio now says the cyclomatic complexity is 1, even though the code is doing the exact same thing. Has the cyclomatic complexity actually been reduced? If so, how?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文