我try 使用switch
语句将整数变量myVar
与字典myDict
中存储的整数值进行比较.
我收到一个错误
类型为‘int’的表达式不能由类型为‘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");
}
}
我做错什么了吗?