方法参数 Ref 与 引用类型

浪尽此生 提交于 2019-11-26 19:38:47

       首先,这篇文章,只是无聊的产物,没什么具体的理论解释。

 

       大家应该都明白,方法的参数前面 加上ref或者out的作用,但是,引用类型的参数前面,添不添加ref,有什么区别呢?

 

如下是一段简单的代码。

 

代码
 1  class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             test a = new test() { ID = 1 };
 6 
 7             test c = new test();
 8 
 9             TestRef b = new TestRef();
10             b.Test(ref a);
11 
12             b.Test(c);
13 
14             Console.WriteLine(string.Format(@" ref value={0}", a.ID));
15             Console.WriteLine(string.Format(@" not ref value={0}", c.ID));
16             Console.ReadLine();
17         }
18     }
19 
20     public class test
21     {
22         public int ID { getset; }
23     }
24 
25     public class TestRef
26     {
27         public void Test(ref test test)
28         {
29             test.ID = 2;
30 
31             Console.WriteLine(string.Format(@" ref value={0}", test.ID));
32             //test = new test() { ID = 5 };
33         }
34 
35         public void Test(test test)
36         {
37             test.ID = 3;
38             Console.WriteLine(string.Format(@" not ref value={0}", test.ID));
39             //test = new test() { ID = 4 };
40         }
41     }

 

 

运行下,相信结果都是大家所想的。

 

但是,去掉代码里面注销掉的那两行,结果呢?

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!