通过一段代码说明C#中rel与out的使用区别
生活随笔
收集整理的這篇文章主要介紹了
通过一段代码说明C#中rel与out的使用区别
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?1using?System;
?2
?3public?partial?class?testref?:?System.Web.UI.Page
?4{
?5????static?void?outTest(out?int?x,?out?int?y)
?6????{//離開這個函數前,必須對x和y賦值,否則會報錯。?
?7????????//y?=?x;?
?8????????//上面這行會報錯,因為使用了out后,x和y都清空了,需要重新賦值,即使調用函數前賦過值也不行?
?9????????x?=?1;
10????????y?=?2;
11????}
12????static?void?refTest(ref?int?x,?ref?int?y)
13????{
14????????x?=x+?1;
15????????y?=?y+1;
16????}?
17
18????protected?void?Page_Load(object?sender,?EventArgs?e)
19????{
20????????//out?test?
21????????int?a,?b;
22????????//out使用前,變量可以不賦值?
23????????outTest(out?a,?out?b);
24????????Response.Write("a={0};b={1}"+a+b);
25????????int?c?=?11,?d?=?22;
26????????outTest(out?c,?out?d);
27????????Response.Write("c={0};d={1}"+c+d);
28
29????????//ref?test?
30????????int?m,?n;
31????????//refTest(ref?m,?ref?n);?
32????????//上面這行會出錯,ref使用前,變量必須賦值?
33
34????????int?o?=?11,?p?=?22;
35????????refTest(ref?o,?ref?p);
36????????Response.Write("o={11};p={22}"?+?o?+?p);
37
38
39????}
40}
41
?2
?3public?partial?class?testref?:?System.Web.UI.Page
?4{
?5????static?void?outTest(out?int?x,?out?int?y)
?6????{//離開這個函數前,必須對x和y賦值,否則會報錯。?
?7????????//y?=?x;?
?8????????//上面這行會報錯,因為使用了out后,x和y都清空了,需要重新賦值,即使調用函數前賦過值也不行?
?9????????x?=?1;
10????????y?=?2;
11????}
12????static?void?refTest(ref?int?x,?ref?int?y)
13????{
14????????x?=x+?1;
15????????y?=?y+1;
16????}?
17
18????protected?void?Page_Load(object?sender,?EventArgs?e)
19????{
20????????//out?test?
21????????int?a,?b;
22????????//out使用前,變量可以不賦值?
23????????outTest(out?a,?out?b);
24????????Response.Write("a={0};b={1}"+a+b);
25????????int?c?=?11,?d?=?22;
26????????outTest(out?c,?out?d);
27????????Response.Write("c={0};d={1}"+c+d);
28
29????????//ref?test?
30????????int?m,?n;
31????????//refTest(ref?m,?ref?n);?
32????????//上面這行會出錯,ref使用前,變量必須賦值?
33
34????????int?o?=?11,?p?=?22;
35????????refTest(ref?o,?ref?p);
36????????Response.Write("o={11};p={22}"?+?o?+?p);
37
38
39????}
40}
41
轉載于:https://www.cnblogs.com/wiyy315/archive/2008/04/15/1155078.html
總結
以上是生活随笔為你收集整理的通过一段代码说明C#中rel与out的使用区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 想买啥 VS 买了啥!理想与现实的差距咋
- 下一篇: [导入]sqlserver2005 数据