1 class Program
2 {
3 //ref 和out类似c++指针,当然也不能拿来直接当指针用,是能引用一些参数,但是不能直接作为地址来控制参数(大概意思)
4 static void Main(
string[] args)
5 {
6 int a, b;
7 OutTest(
out a,
out b);
8 Console.WriteLine(
"a={0},b={1}",a,b);
9 //output a = 1;b = 2;
10
11 int c =
11, d =
22;
12 OutTest(
out c,
out d);
13 Console.WriteLine(
"a={0},b={1}", a, b);
14 //output c = 1;d = 2;
15
16 int m =
11, n =
22;
17 //RefTest(ref m, ref n);
18 RefTest(
ref m,
ref n);
19 Console.WriteLine(
"m={0},n={1}", m, n);
20 //output m = 22;n = 11;
21
22 Swap(m, n);
23 Console.WriteLine(
"m={0},n={1}", m, n);
24 //output m = 22;n = 11;
25 }
26
27 static void OutTest(
out int x,
out int y)
28 {
29 //方法体外可以不用对传出参数赋值
30 //方法体内,必须对传出的参数赋值,否则报错,例如:x=y;
31 //适用于多个返回值的函数
32 x =
1;
33 y =
2;
34 }
35
36 static void RefTest(
ref int x,
ref int y)
37 {
38
39 //方法体外,必须对参数赋值,否则报错
40 //方法体内,ref对参数可以赋值也可以不赋值
41 //适合引用原值,并对原值修改
42 int temp =
x;
43 x =
y;
44 y =
temp;
45 }
46
47 static void Swap(
int a,
int b)
48 {
49 int temp =
a;
50 a =
b;
51 b =
temp;
52 }
53 }
转载请注明地址:http://www.cnblogs.com/Vincentblogs/p/4083028.html
QQ群:346738352 Unity技术交流群,讲纯粹的技术。
转载于:https://www.cnblogs.com/Vincentblogs/p/4082997.html
相关资源:C#中ref,out和params有什么区别