【问题标题】:Use of switch with logic operators on C# [duplicate]在 C# 上使用带有逻辑运算符的 switch [重复]
【发布时间】:2021-12-24 10:32:20
【问题描述】:

我是 C# 初学者。为什么在“case 6:”行出现错误(Compiler Error CS0152, A label was repeat in a switch statement.switch statement contains multiple case with the value of tag '6'),当我写这段代码时:

namespace ConsoleApp1
{
    class Class1
    {
        public int abc { get; set; } 

        public Class1()
        {
            
        }

        public void mTest(int aVal)
        {
            switch(aVal)
            {
                case (2 | 4):
                {
                    break;
                }
                case 5:
                    {
                        break;
                    }
                case 6:
                    {
                        break;
                    }
            }
        }
    }
}

【问题讨论】:

  • 2 | 4 是等于6 的位运算。 6 有两种情况,这是不允许的。如果你想测试 2 或 4,你必须写 case 2: case 4: your_code; break;(多行)。

标签: c# switch-statement


【解决方案1】:

你快到了,但模式匹配该条件的正确方法是:

case 2 or 4:
    break;

【讨论】:

  • 这是一个很好的答案,其他 dup OP 的答案中没有。
猜你喜欢
  • 1970-01-01
  • 2013-11-25
  • 2013-04-03
  • 1970-01-01
  • 1970-01-01
  • 2013-12-21
  • 1970-01-01
  • 2012-11-17
  • 1970-01-01
相关资源
最近更新 更多