2 回答

TA貢獻(xiàn)1783條經(jīng)驗(yàn) 獲得超4個(gè)贊
class Solution
{
static int[] foo(int[] array)
{
int[] xx = new int[array.Length]; // Building this but not using it
for (int i = 0; i < array.Length; i++)
{
array[i] *= 2; //Altering the input array changes the array in the Main method..
Console.WriteLine(array[i]);
}
return array;
}
static void Main(string[] args)
{
int[] array = new int[4] { 73, 67, 38, 33 };
foo(array); // Not assigning the values to an object.
//After this step look at array it will be 146, 134, 76 , 66
}
}
所以你正在改變 foo 方法中的原始數(shù)組。您正在傳遞數(shù)組對(duì)象,然后覆蓋這些值。
您聲明了一個(gè)新的 int[] xx 但隨后什么都不做,我認(rèn)為您應(yīng)該將源數(shù)組復(fù)制到新的 xx int[]。這樣做不會(huì)改變主方法中的原始整數(shù)。然后,您可以在 main 方法中分配新數(shù)組的返回值。下面的例子:
class Solution
{
static int[] foo(int[] array)
{
int[] xx = new int[array.Length];
//Copy the array into the new array
Array.Copy(array, xx, array.Length);
for (int i = 0; i < xx.Length; i++)
{
xx[i] *= 2;
Console.WriteLine(xx[i]);
}
return xx;
}
static void Main(string[] args)
{
int[] array = new int[4] { 73, 67, 38, 33 };
//Assign the new array to an object
int[] newArray = foo(array);
}
}
編輯:我還看到您在頂部包含了 linq,如果您對(duì)使用 linq 感興趣,這將獲得相同的結(jié)果:
static void Main(string[] args)
{
int[] array = new int[4] { 73, 67, 38, 33 };
int[] newarr = array.Select(arrayvalue => arrayvalue * 2).ToArray();
}

TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超3個(gè)贊
您當(dāng)前的代碼確實(shí)返回一個(gè)數(shù)組,但您是:
更新值
array
而不是新xx
數(shù)組不分配返回值
Main
這是您修改現(xiàn)有數(shù)組而不是新數(shù)組的地方:
static int[] foo(int[] array)
{
int[] xx = new int[array.Length];
for(int i = 0; i < array.Length; i++)
{
// NOTE: modifying array, not xx
array[i] *= 2;
Console.WriteLine(array[i]);
}
// NOTE: returning array, not xx -- xx is not used
return array;
}
這是返回?cái)?shù)組的缺失賦值:
static void Main(string[] args)
{
int[] array = new int[4] {73, 67, 38, 33 };
// You are not assigning the returned array here
int[] newArray = foo(array);
}
ref如果您需要更改數(shù)組大小,您的另一個(gè)選擇是將數(shù)組作為參數(shù)傳遞:
static int[] foo(ref int[] array)
{
// Modify array as necessary
}
- 2 回答
- 0 關(guān)注
- 204 瀏覽
添加回答
舉報(bào)