asp教程.net数组 ref和out传递数组
与所有的out参数一样,在使用数组类型的out参数前必须先为其赋值,即必须由被调用方为其赋值
class testarraysclass
{
static void main()
{
//declare and initialize an array
int[,] thearray = new int[5,10];
system.console.writeline("the array has {0} dimensions",thearray.rank);
}
}
//output:the array has 2 dimensions
数组实际上是对象【.net的所有对象都是派生自object对象】,而不只是像c和c++中那样的可寻址连续内存区域。array是所有数组是所有数组类型的抽象基类型。可以使用array具有属性以及其他成员。例如使用length属性来获取数组的长度:
int[] number = {1,2,3,4}
int lengthofnumbers = number.length;
使用ref和out传递数组
。例如:
static void testmethod1(out int[] arr)
{
//definite assignment of array
arr = new int[10];
}
与所有的ref参数一样,数组类型的ref参数必须由调用方明确赋值。因此不需要由接受方明确赋值。可以将数组类型的ref参数更改为调用的结果。
例如,可以为数组赋以null值,或将其初始化为另一个数组。例如:
static void testmethod2(ref int[] arr)
{
// arr initalized to a different array
arr = new int[10];
}
下面我们用2个示例来说明out与ref在将数组传递给方法时的用法差异。
在此例中,在调用方(main方法)中声明数组thearray,并在fillarray方法中初始化此数组。然后将数组元素返回调用方并显示。
class testout
{
static void fillarray(out int[] arr)
{
arr = new int[5] {1,2,3,4,5};
}
static void main()
{
int[] thearray;
fillarray(out thearray);
system.console.writeline("array elements are:");
for(int i=0;i{
system.console.write(thearray[i] +" ");
}
system.console.writeline("press any key to exit.");
}
}
在下例中,在调用方(main方法)中初始化数组thearray,并通过使用ref参数将其传递给fillarray方法。 在fillarray方法中更新某些数组元素。然后将数组元素返回调用并显示。
class testref
{
static void fillarray(ref int[] arr)
{
int (arr == null)
arr = new int[10];
}
arr[0] = 1111;
arr[4] = 5555;
}
static void main()
{
int[] thearray = {1,2,3,4,5};
fillarray(ref thearray);
system.console.writeline("array elements are:");
for (int i = 0; i < thearray.length; i++)
{
system.console.write(thearray[i] + " ");
}}
ps教程:注意理解out与ref的不同。
茶杯头甜蜜终章dlc 官方手机版v1.0.0.3
下载火柴人传说暗影格斗内置菜单 最新版v3.0.1
下载荒野乱斗测试服 安卓版v61.10.3
下载荒野乱斗彩虹服 安卓版v61.10.3
下载寒霜启示录 安卓版v1.25.10
寒霜启示录是一款生存模拟游戏,不少玩家可能对于末日都有着自己
末日城堡免广告版 安卓最新版v0.7.1
末日城堡免广告版是一款非常好玩的模拟经营类游戏,内部可以不看
甜蜜人生模拟器 最新版v1.4.5
甜蜜人生模拟器是一款非常好玩的模拟恋爱手游,玩家在这里能够对
武器锻造师内置功能菜单 v10.4
武器锻造师内置菜单版是游戏的破解版本,在该版本中为玩家提供了
开放空间overfield 安卓版v1.0.5
开放空间Overfield是一款箱庭养成经营手游,让你在广阔