作者tkcn (小安)
看板java
标题Re: [问题] 请问call by address
时间Tue Mar 20 17:12:26 2007
下面是 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