【问题标题】:How to initialize an array in c# [duplicate]如何在c#中初始化一个数组[重复]
【发布时间】:2018-08-05 14:03:15
【问题描述】:

嘿,我正在尝试在 c# 中初始化一个数组,但不知道为什么这不起作用

Wave currentWave = new Wave(
                                {
                                    {1, 1, 1}, 
                                    {1, 1},
                                    {1, 1, 1}
                                }, 
                                    {3, 2}
                                );

private class Wave {
    private int currentLoad;
    private int[] aTimesToNextLoad;
    private int[][] aEnemieLoads;

    public Wave(int[][] aEnemiesToLoad, int[] aTimesToNextLoad) {
        this.aEnemieLoads     = aEnemieLoads;
        this.aTimesToNextLoad = aTimesToNextLoad;
    }
}

我得到了大约 18 个语法错误。我也试过使用new int[][] {...},然后我收到这条消息:

数组初始值设定项只能用于变量或字段初始值设定项。尝试改用新表达式

解决办法是什么?

【问题讨论】:

  • 不相关,但 this.aEnemieLoads = aEnemieLoads 是错误的 - 参数称为 aEnemiesToLoad,您将字段分配给自身(查看编译警告)。

标签: c# arrays initialization


【解决方案1】:

好吧,我仍然不知道为什么代码不起作用,但这解决了问题。

Wave currentWave = new Wave(new int[][]
                            {
                                new int [] {1, 1, 1}, 
                                new int [] {1, 1},
                                new int [] {1, 1, 1}
                            }, 
                                new int [] {3, 2}
                            );

【讨论】:

  • 请注意,在问题中我只使用了两次'new int'。一个用于整个第一个数组,一个用于第二个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-08
  • 2012-04-30
  • 2012-02-02
  • 1970-01-01
  • 2019-03-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多