声明一个队列数组

dee*_*ner -2 c# arrays syntax array-initialization

我的代码中存在什么语言语法问题?我想声明一个队列数组。这是声明和使用它们的正确方法吗?

   public static void Main(string[] args)
    {
        Queue<int>[] downBoolArray = new Queue<int>[8]();
        downBoolArray[0].Enqueue(1);
    }
Run Code Online (Sandbox Code Playgroud)

Ste*_*edy 6

您的第一个问题是语法错误:new Queue<int>[8]()应该是new Queue<int>[8].

一旦使用正确的语法声明,当您尝试使用数组 ( downBoolArray[0].Enqueue(1)) 的元素时,您将遇到 NullReferenceException 因为数组元素初始化为其默认值,在引用类型的情况下为null

您可以使用单行 LINQ 使用非空种子值初始化数组:

Queue<int>[] downBoolArray = Enumerable.Range(1,8).Select(i => new Queue<int>()).ToArray();
Run Code Online (Sandbox Code Playgroud)

Range指定序列中需要 8 个“条目”的参数;该语句为每个项目Select创建一个新项目;Queue<int>并且ToArray调用将我们的序列输出为数组。