2 回答

TA貢獻1828條經驗 獲得超3個贊
但這意味著您可以在不傳遞 Ref 關鍵字的情況下更改引用。你可以在一個子方法中做到這一點
這不是真的。雖然你可以改變參考中的RemoveAt-方法,這一變化不會影響傳遞給它的參考。您只需將新的(調整大小的)實例扔掉即可。當您想將引用更改為指向某個其他實例時,您的方法應該具有 -ref關鍵字。
在其他關鍵字中,您的第二個代碼也可以這樣編寫:
public static void RemoveAt<T>(arr, int index)
{
for (int a = index; a < arr.Length - 1; a++)
{
arr[a] = arr[a + 1];
}
var reference = arr;
Array.Resize(ref reference, arr.Length - 1);
}
雖然reference在調用后當然會改變Array.Resize,但arr會保持不變。它們引用了完全不同的實例。

TA貢獻1852條經驗 獲得超1個贊
功能不會一樣。Resize可以將引用更改為arr,因此在第一種情況下,您將更改調用方的外部引用,如果沒有,ref您將只會更改本地方法引用。
參考:
var extArr = new object[100];
RemoveAt(ref extArr, 10); // The arr variable in this method is now the exact same physical
// variable as extArr.
// extArr is now a completely valid reference to the resized array, business as usual.
沒有:
var extArr = new object[100];
RemoveAt(extArr , 10); // The copy of the reference (arr) is updated in this method
//internally, but the local variable extArr is only copied and not modified
// extArr is now a reference to the old, not-resized array.
// Note that the element is still "removed", overwritten in the for loop,
// but the resized copy of the array is lost and has no references to it.
- 2 回答
- 0 關注
- 202 瀏覽
添加回答
舉報