【问题标题】:Invalid expression term '{' (Declaring array outside switch statement)无效的表达式术语“{”(在 switch 语句之外声明数组)
【发布时间】:2015-12-29 06:18:58
【问题描述】:

我已经为一个程序启动了一个算法,并且我已经在方法本身中声明了数组。但是,当我在 switch 语句中引用数组时,会出现重复错误: Invalid expression term '{' and '{' expected and ';'预期的 下面是代码:

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;
    }
}

你如何解决这个问题?

【问题讨论】:

  • 基本问题是你使用Java风格声明数组,这不是有效的C#语法

标签: c# arrays


【解决方案1】:

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

【讨论】:

  • 或者您可以省略int,而只使用new[] {10,20,30,40}。由于间隔已被声明为int[]
  • @KevinWells 一个小问题:这不是因为interval 被定义为int[],而是因为10 等是int 文字。 C# 不会查看目的地来推断类型(lambda 除外)。它首先推断类型,然后检查它是否与分配兼容。例如,如果你写了new[] { 10.0 },这将导致一个编译错误,double[] 不能分配给int[]
  • 好点子,感谢您的澄清,我的脑子里完全倒退了
【解决方案2】:

法比奥的回答是正确的。但是它可以用来进一步改进您的代码:

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];

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 2020-09-23
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多