Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 初始化二维对象数组_C# - Fatal编程技术网

C# 初始化二维对象数组

C# 初始化二维对象数组,c#,C#,我有一个二维的对象数组,我使用传统的循环初始化它: PairDS[,] tempPb1 = new PairDS[LoopCounterMaxValue+1, LoopCounterMaxValue+1]; for (int i = 0; i <= LoopCounterMaxValue; i++) for (int j = 0; j <= LoopCounterMaxValue; j++) tempPb1[i, j] = new PairDS(); PairDS

我有一个二维的对象数组,我使用传统的循环初始化它:

PairDS[,] tempPb1 = new PairDS[LoopCounterMaxValue+1, LoopCounterMaxValue+1];
for (int i = 0; i <= LoopCounterMaxValue; i++)
   for (int j = 0; j <= LoopCounterMaxValue; j++)
      tempPb1[i, j] = new PairDS();
PairDS[,]tempb1=新的PairDS[LoopCounterMaxValue+1,LoopCounterMaxValue+1];

对于(int i=0;i我不认为可以直接将多维数组表示为可枚举或列表,因为它(CLR)无法知道您打算如何为数组编制索引


如果你真的一行一行地计算出来,结果会更糟然后在执行操作时简单地在数组中循环并初始化每个单元格。

无法使用可枚举类型直接初始化2D数组,正如一些用户指出的,您所做的操作没有直接错误。如果您只是想简化循环,那么这可能就是您想要的争取

const int length = LoopCounterMaxValue + 1;
PairDS[,] tempPb1 = new PairDS[length, lenth];
for (var i = 0; i < length * length; i++) {
  var column = i % length;
  var row = (i - column) / length;
  tempPb1[row, column] = new PairDS();
}
const int length=LoopCounterMaxValue+1;
PairDS[,]tempb1=新PairDS[长度,长度];
对于(变量i=0;i
我以为
初始化
可以做到,但它只适用于值类型

int N = 10;
PairDS[,] temp = new PairDS[N + 1, N + 1];
temp.Initialize();
我建议您使用锯齿状数组

class PairDS { public PairDS(int row, int col) { } }


static void Main(string[] args)
{
    int N = 10;
    PairDS[][] temp = Enumerable.Range(0, N + 1).Select(
        (row) => Enumerable.Range(0, N + 1).Select(
            (col) => new PairDS(row, col)).ToArray()).ToArray();
}

没什么,但它看起来确实很冗长。那些操作%、/、*并不简单,需要更多的时间来理解正在发生的事情…@archer我认为它是关于透视的。我个人觉得它更容易阅读,因为我已经用过很多次,也看到过很多次了。我确信一眼就看不到它的简单性。OP的问题不清楚他们的意图,我不想o通过移除nestingYes锯齿阵列来简化。这是另一个值得考虑的好主意。感谢您的合作。