Why not use a collection class List or ArrayList which has .Add
methods
Possible to assign the Length of an array through a function with parameters?
質問
I'm having about 4 int arrays that need their length calculated, assigned to them and then populated. I was trying to thin out the code by using a function with parameters, instead of repeating long calculations 4 times, but I can't seem to set the length by designating the array as a parameter. I tried something like the code below:
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];
}
Most of the code seems to work, except for the length assigning part. Any ideas?
解決 2
他のヒント
If you need to reallocate the array within method and want it to update the variable you've passed as method parameter you have to make the parameter ref
or out
:
SetLength(ref int[] array)
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);
You can do it without ref
modifier as MarcinJuraszek suggests like this
for(int i=0; i<4; i++)
if(i==0) array1 = SetLength();
else if(i==1) array2 = SetLength();
else if(i==2) array3 = SetLength();
else if(i==3) array4 = SetLength();
int[] SetLength()
{
//calculations for length here
//int result=...;
var array = new int[result];
//getting info for populating the array
for(int i=0; i < result; i++)
array[i] = some_value[i];
return array;
}
And by the way, you don't really need a cycle here. For your original code
SetLength(array1);
SetLength(array2);
SetLength(array3);
SetLength(array4);
would suffice.