下面是 C# 的程式碼,
---
static void callByAddr(ref string param) {
Console.WriteLine("before change: " + param);
param = "abc";
Console.WriteLine("after change: " + param);
}
static void Main(string[] args) {
string str = "123";
Console.WriteLine("before call: " + str);
callByAddr(ref str);
Console.WriteLine("after call: " + str);
}
---
output:
---
before call: 123
before change: 123
after change: abc
after call: abc
---
str 是我要傳遞的參數,
因為使用了 ref 修飾,因此傳遞的內容是 str 的 address。
所以當我 assign 其他的值給 param,同時也會影響 str,
因為 str 與 param 其所 bind 的記憶體位址相同。
補充一點個人淺見,
坊間一些 C/C++ 書籍會將 foo( &obj ) 認定為 call by address,
我想這是因為真正要傳遞的參數是 obj (我並非指實作面)
而傳遞 address 只是一種為了達到 side-effect 手段,
因此其實我認為,稱呼這種情況為 call by address 其實也未嘗不可。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.131.70.198