-- 作者:admin
-- 发布时间:11/9/2004 2:25:00 AM
-- C#快餐-5
发信人: walts (休息一会), 信区: DotNET 标 题: C#快餐-5 发信站: BBS 水木清华站 (Thu Jul 26 01:25:22 2001) Lesson 5. Passing by value and by reference Here is a simple program that attempts to modify an integer. using System; //does not change value of k class Demo { public class Test { public void change (int k) { k=k+2; } } public static void Main() { int i=3; Test hi=new Test(); Console.WriteLine("Before {0} ", i); hi.change(i); Console.WriteLine("After {0} ", i); } } If you compile and execute this program you will find that the value of the integer have not been changed by method change. The reason is quite simple: method change takes a value of i, makes a copy of it, adds 2 to the copy and returns control to the main. Value of i does not change.When change returns, its local copy of variable i disappears ( goes out of scope). When Console.WriteLine("After {0} ",i); is called, it uses i which was never changed. A simple fix is to modify method change so that it returns a value: using System; // Circumvent the problem of changing value of i. class Demo { public class Test{ public int change (int k) { return k+2; } } public static void Main() { int i=3; Test hi=new Test(); Console.WriteLine("Before {0} ",i); Console.WriteLine("After {0} ", hi.change(i)); } } The code above works fines but it does not change the value of i. To change i we need to pass it by reference. When passing by reference compiler changes i instead of changing a local copy. To do this we need to add keyword ref indicating that change takes a reference as an argument. using System; class Demo { public class Test{ public void change(ref int k) { k=k+2; } } public static void Main() { int i=3; Test hi=new Test(); Console.WriteLine("Before {0} ", i); hi.change(ref i); Console.WriteLine("After {0} ", i); } } The output of this program is: Before 3 After 5 -- A great poem is a fountain forever overflowing with the waters of wisdom and delight. —— Shelley ※ 来源:·BBS 水木清华站 smth.org·[FROM: 166.111.142.118] 上一篇 返回上一页 回到目录 回到页首 下一篇
|