会员
众包
新闻
博问
AI培训
云市场
所有博客
当前博客
我的博客
我的园子
账号设置
简洁模式
...
退出登录
注册
登录
猪
不再找借口............
博客园
首页
新随笔
联系
订阅
管理
使用 ref 和 out 传递数组
与所有的out 参数一样,在使用数组类型的ref 参数前必须先为其赋值,即必须由被调用方为其赋值。
程序如下:
1
在此例中,在调用(Main 方法)中声明数组 theArray,并在 FillArray 方法中初始化此数组。然后将数组元素返回调用方并显示。
2
class
TestOut
3
{
4
static
void
FillArray(
out
int
[] arr)
5
{
6
//
Initialize the array:
7
arr
=
new
int
[
5
]
{
1
,
2
,
3
,
4
,
5
}
;
8
}
9
10
static
void
Main()
11
{
12
int
[] theArray;
//
Initialization is not required
13
14
//
Pass the array to the callee using out:
15
FillArray(
out
theArray);
16
17
//
Display the array elements:
18
System.Console.WriteLine(
"
Array elements are:
"
);
19
for
(
int
i
=
0
; i
<
theArray.Length; i
++
)
20
{
21
System.Console.Write(theArray[i]
+
"
"
);
22
}
23
}
24
}
程序输出结果如下:
25
Array elements are:
26
27
1
2
3
4
5
28
在此例中,在调用(Main 方法)中初始化数组 theArray,并通过使用
ref
参数将其传递给 FillArray 方法。在 FillArray 方法中更新某些数组元素。然后将数组元素返回调用方并显示。
29
class
TestRef
30
{
31
static
void
FillArray(
ref
int
[] arr)
32
{
33
//
Create the array on demand:
34
if
(arr
==
null
)
35
{
36
arr
=
new
int
[
10
];
37
}
38
//
Fill the array:
39
arr[
0
]
=
1111
;
40
arr[
4
]
=
5555
;
41
}
42
43
static
void
Main()
44
{
45
//
Initialize the array:
46
int
[] theArray
=
{
1
,
2
,
3
,
4
,
5
}
;
47
48
//
Pass the array using ref:
49
FillArray(
ref
theArray);
50
51
//
Display the updated array:
52
System.Console.WriteLine(
"
Array elements are:
"
);
53
for
(
int
i
=
0
; i
<
theArray.Length; i
++
)
54
{
55
System.Console.Write(theArray[i]
+
"
"
);
56
}
57
}
58
}
59
程序输出结果如下:
60
Array elements are:
61
62
1111
2
3
4
5555
63
posted @
2008-12-20 14:47
悟〈--觉
阅读(
342
) 评论(
2
)
编辑
收藏
举报
会员力量,点亮园子希望
刷新页面
返回顶部
公告