亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

子使用 Ref 時需要關鍵字 Ref?

子使用 Ref 時需要關鍵字 Ref?

C#
慕容708150 2021-12-05 14:46:47
我在這個問題上找到了這個方法public static void RemoveAt<T>(ref T[] arr, int index){    for (int a = index; a < arr.Length - 1; a++)    {        arr[a] = arr[a + 1];    }    Array.Resize(ref arr, arr.Length - 1);}現在我想知道是否ref需要在嵌套方法中使用它?方法也可能是:public static void RemoveAt<T>(T[] arr, int index) //ref removed具有相同的功能?我已經對其進行了測試并且它有效 - 但這意味著您可以在不傳遞Ref關鍵字的情況下更改引用。你可以在子方法中做到這一點。
查看完整描述

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會保持不變。它們引用了完全不同的實例。


查看完整回答
反對 回復 2021-12-05
?
小怪獸愛吃肉

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.


查看完整回答
反對 回復 2021-12-05
  • 2 回答
  • 0 關注
  • 202 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號