无效的表达式项';{';(在switch语句外声明数组)

本文关键字:语句 数组 switch 声明 表达式 无效 | 更新日期: 2023-09-27 18:28:14

我已经为一个程序启动了一个算法,并在方法本身中声明了数组。但是,当我在switch语句中引用数组时,我会得到重复的错误:应为无效的表达式项"{"answers"{",应为";"以下是代码:

algorithm()
{
code .....
int[] interval;
more code....
switch (int.parse(lbl2.text))
    {
    case 1:
        sInterval = {10, 20, 30, 40};
        break;
    case 2:
        sInterval = { 50, 60, 70, 80};
        break;
    }
}

你如何解决这个问题?

无效的表达式项';{';(在switch语句外声明数组)

正确的语法是new int[]{10, 20, 30, 40}

Fábio的答案是正确的。然而,它可以用来进一步改进您的代码:

var sIntervals = new Dictionary<int, int[]>()
{
    { 1, new[] { 10, 20, 30, 40} },
    { 2, new[] { 50, 60, 70, 80} },
    // you can easily add intervals here
};
// you can get interval simple like this
// var sInterval = sIntervals[1];

下一步是用tryparse替换parse,以避免出现异常。