You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用switch语句比较int变量与字典中int值报错,if语句却正常?

问题描述

尝试用switch语句比较整数变量myVar和字典myDict中存储的整数值时触发错误:

An expression of type 'int' cannot be handled by a pattern of type 'myDict[]'

报错代码如下:

Dictionary<string, int> myDict = new Dictionary<string, int>()
    {
        ["Mary"] = 1,
        ["John"] = 2
    }; 

void MyMethod()
{
    int myVar = 1;

    switch (myVar)
    {
        case myDict["Mary"]:  // Error here
            Console.WriteLine("Okay");
            break;
    }
}

但换成if语句就能正常运行:

Dictionary<string, int> myDict = new Dictionary<string, int>()
    {
        ["Mary"] = 1,
        ["John"] = 2
    }; 

void MyMethod()
{
    int myVar = 1;

    if (myVar == myDict["Mary"])  // Works just fine
    {
        Console.WriteLine("Okay");
    }
}
问题原因

C# 的switch case分支要求case标签必须是常量表达式,myDict["Mary"]属于运行时才能确定值的变量表达式,不符合语法规则。而if语句中的==比较是运行时的数值比对,没有常量要求,因此可以正常执行。

解决方法

有两种常用修复方式:

  • 若字典值不会变动,提前将其赋值给常量:
    const int MaryValue = 1;
    Dictionary<string, int> myDict = new Dictionary<string, int>()
        {
            ["Mary"] = MaryValue,
            ["John"] = 2
        }; 
    
    void MyMethod()
    {
        int myVar = 1;
    
        switch (myVar)
        {
            case MaryValue:
                Console.WriteLine("Okay");
                break;
        }
    }
    
  • 使用C# 7.0及以上支持的switch when子句,通过条件判断实现:
    Dictionary<string, int> myDict = new Dictionary<string, int>()
        {
            ["Mary"] = 1,
            ["John"] = 2
        }; 
    
    void MyMethod()
    {
        int myVar = 1;
    
        switch (myVar)
        {
            case int val when val == myDict["Mary"]:
                Console.WriteLine("Okay");
                break;
        }
    }
    

内容的提问来源于stack exchange,提问作者Janna Ukoko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 21:55:11