行者无疆
When I was young , I used to think that money was the most important thing in life , now I am old , I know it is.
值类型作为参数的时候,传递的是值类型本身在栈上的值。引用类型作为参数的时候,传递的是引用类型本身在栈上的引用(相当于指针)而不是其指向的堆上的值。 String除外,string会被当值类型处理。当方法调用的时候, 首先是在栈上创建参数的copy, 然后把传进来的值附上。

例子:

如值类型传递                                private static void intTest(int a, int b)

                {

                        int c = a;

                        a = b;

                        b = c;

}

int a1 = 1;

                int b1 = 2;

intTest(a1, b1);

那么执行此intTest(a1, b1);,首先是在栈上创建 两个int型的变量a和b(a和b是方法参数),然后把a1的值赋给a,b1赋值给b。 所以值类型的参数传递,不会改变函数外部代码的值。

引用型传递private static void test(classA s1, classA s2)

{

classA s3 = s1;

        s1 = s2;

        s2 = s3;

}

classA a = new classA();

                classA b = new classA();

                a.num = 1;

                b.num = 2;

                test(a, b);

那么执行到test(a, b);,首先是在栈上创建两个ClassA类型的变量s1, s2, 然后把a在栈上的引用赋值给s1所指向的堆,换而言之,同样s2指向的堆的值为      b在栈上的引用。

然后再函数里创建了s3, s3指向的堆里的值是s1的引用,然后改变s1和s2都是改变的s1和s2指向的堆的位置,而不会影响到a和b的堆。
posted on 2012-07-13 11:34  衣不如新  阅读(129)  评论(0)    收藏  举报