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

 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

 

转载于:https://www.cnblogs.com/derickzhao/p/7256088.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值