Van*_*alk 0 c# arrays loops assign
我有大约4个int数组,需要计算它们的长度,分配给它们然后填充.我试图通过使用带参数的函数来稀释代码,而不是重复4次长计算,但我似乎无法通过将数组指定为参数来设置长度.我尝试过类似下面的代码:
for(int i=0; i<4; i++)
if(i==0) SetLength(array1);
else if(i==1) SetLength(array2);
else if(i==2) SetLength(array3);
else if(i==3) SetLength(array4);
SetLength(int[] array)
{
//calculations for length here
//int result=...;
array = new int[result];
//getting info for populating the array
for(int i=0; i<result; i++)
array[i]=some_value[i];
}
Run Code Online (Sandbox Code Playgroud)
除了长度分配部分之外,大多数代码似乎都有效.有任何想法吗?
如果需要在方法中重新分配数组并希望它更新您作为方法参数传递的变量,则必须创建参数ref或out:
SetLength(ref int[] array)
Run Code Online (Sandbox Code Playgroud)
for(int i=0; i<4; i++)
if(i==0) SetLength(ref array1);
else if(i==1) SetLength(ref array2);
else if(i==2) SetLength(ref array3);
else if(i==3) SetLength(ref array4);
Run Code Online (Sandbox Code Playgroud)