对象和类型(数组、ref、out)

2018-06-17 19:06:35来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

 1 class Program
 2     {
 3         //数组是引用类型
 4         //如果把数组或类等其他引用类型传递给方法,对应的方法就会使用该引用类型改编数组中值,
 5         //而新值会反射到原始数组上
 6         static void SomeFunction(int[] ints, int i)
 7         {
 8             ints[0]= 100;
 9             i = 10;
10         }
11 
12         //ref参数;使用关键字的参数会,方法会影响到对应参数的数值改变
13         //而且ref参数需要初始化
14         static void SomeFunction1(ref int j)
15         {
16             j = 100;
17         }
18 
19         //out参数;out参数可以不需要初始化
20         //该参数通过引用传递,方法返回w是会保留对w数值的改变
21         static void SomeFunction2(out int w)
22         {
23             w = 100;
24         }
25 
26         static void Main(string[] args)
27         {
28             #region SomeFunction
29 
30             int[] ints = { 1, 2, 3, 4 };
31             int i = 1;
32 
33             SomeFunction(ints, i);
34 
35             Console.WriteLine(ints[0]);
36             Console.WriteLine(i);
37 
38 
39             //输出结果:100,1
40             //其中i的之是没有变化的
41 
42             #endregion
43 
44             #region SomeFunction1
45 
46             int j = 1;//正确
47             //int j;//错误
48 
49             SomeFunction1(ref j);
50 
51             Console.WriteLine(j);
52 
53             //输出结果:100
54             //j的数值发生改变
55 
56             #endregion
57 
58             #region SomeFunction2
59 
60             int w;//正确
61             //int w = 1;//正确
62             
63             SomeFunction2(out w);
64 
65             Console.WriteLine(w);
66 
67             //输出结果:100
68             //w的数值发生改变
69             
70             #endregion
71         }
72     }
View Code

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:对象和类型(结构、弱引用、扩展方法)

下一篇:什么是web service (转)