Code
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace zhongzhi
6 {
7 public class test
8 {
9 public int x;
10 }
11 class Program
12 {
13 public void change(int x)
14 {
15 x = x * 10;
16 }
17 public void change2(test obj)
18 {
19 obj.x = obj.x * 10;
20 }
21
22 static void Main(string[] args)
23 {
24 int x = 5;
25 Program p = new Program();
26 p.change(x);
27
28 Console.WriteLine("chang改变后x={0}",x);
29 test t = new test();
30 t.x=x;
31 Console.WriteLine("t.x={0}",x);
32 p.change2(t);
33 Console.WriteLine("chang2改变后={0}",t.x);
34 Console.ReadLine();
35 }
36 }
37 }
38
39
运行结果:
chang改变后x=5
t.x=5
chang2改变后x=50;
通过上面可以看到int是值类型,他不能引用,只是拷贝一个副本,
test类是可以引用的
如果想要chang方法来改变x的值则需要加上ref 引用的时候也要加ref
看下面代码 :
Code
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace zhongzhi
6 {
7 public class test
8 {
9 public int x;
10 }
11 class Program
12 {
13 public void change( ref int x)//加上ref
14 {
15 x = x * 10;
16 }
17 public void change2(test obj)
18 {
19 obj.x = obj.x * 10;
20 }
21
22 static void Main(string[] args)
23 {
24 int x = 5;
25 Program p = new Program();
26 p.change(ref x);//加上ref
27
28 Console.WriteLine("chang改变后x={0}",x);
29 test t = new test();
30 t.x=x;
31 Console.WriteLine("t.x={0}",x);
32 p.change2(t);
33 Console.WriteLine("chang2改变后={0}",t.x);
34 Console.ReadLine();
35 }
36 }
37 }
38
39
此时运行结果如下:
chang改变后x=50
t.x=50
chang2改变后x=500;
这个时候我们可以看到:所有的值都改变了!
如果我们只想要change x=50,其他的不变怎么办?只要改变位置即可,看代码:
Code
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace zhongzhi
6 {
7 public class test
8 {
9 public int x;
10 }
11 class Program
12 {
13 public void change( ref int x)//加上ref
14 {
15 x = x * 10;
16 }
17 public void change2(test obj)
18 {
19 obj.x = obj.x * 10;
20 }
21
22 static void Main(string[] args)
23 {
24 int x = 5;
25
26 Program p = new Program();
27
28 test t = new test();
29 t.x=x;
30 Console.WriteLine("t.x={0}",x);
31 p.change2(t);
32 Console.WriteLine("chang2改变后={0}",t.x);
33
34 //改变位置
35 p.change(ref x);//加上ref后引用函数
36 Console.WriteLine("chang改变后x={0}",x);
37
38 Console.ReadLine();
39 }
40 }
41 }
42
43
运行结果:
t.x=5
chang2改变后x=50;
change改变后x=50