我想动态调整数组的大小。一切都会好的,但在示例中我发现有人使用 Array.Resize() 来调整一维数组的大小,但我希望有可能创建锯齿状数组。我从文件行中读取,其中可能是一些由空格分隔的数字 - 因此我需要动态创建的锯齿状数组。 这是我使用它时的类,但我的数组不调整大小:(
class Program
{
int[][] nodesMatrix = null;
private void ReadFromFile(string fileName)
{
string line;
int nodesNr;
if(File.Exists(fileName) )
{
StreamReader fileReader = null;
try
{
fileReader = new StreamReader(fileName);
int lineNr = 0;
while ((line = fileReader.ReadLine()) != null)
{
int connectionsNr = 0;
if (lineNr==0)
{
nodesNr = Convert.ToInt32(line);
nodesMatrix = new int[nodesNr][];
for (int i = 0; i < nodesNr;i++ )
{
nodesMatrix[i] = new int[1];
}
}
else
{
string tmpNumber = null;
foreach (char sign in line)
{
if (sign != ' ')
{
tmpNumber += sign;
}
if (sign == ' ')
{
if (tmpNumber != null)
{
//nodesMatrix[lineNr] = new int[connectionsNr+1];
nodesMatrix[lineNr][connectionsNr] = Convert.ToInt32(tmpNumber);
connectionsNr++;
Array.Resize<int>(ref nodesMatrix[lineNr], connectionsNr); //here i try to resize array
}
tmpNumber = null;
}
}
}
lineNr++;
}
}
finally
{
if (fileReader != null)
fileReader.Close();
}
}
也许你知道怎么做?
最佳答案
也许我不理解您的用例,但在我看来,如果您知道需要调整大小的数据结构,那么最好使用列表或相关结构,而不是数组。您始终可以通过 linq 添加的 .ToArray() 扩展将列表最后转换回数组。
同样,如果您使用泛型,您可以确保拥有一个强类型的多维列表。您同样可以在内部使用一对列表,并创建自己的类来包装它们。
关于c# - 动态调整数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2374300/