六
.
其
他
System.Array
是所有数组类型的抽象基类型。
例如
:
int[] a = {1, 2, 3, 4, 5};
int LengthOfNumbers = a.Length;
System.Array 类提供许多有用的其他方法 /属性 ,如用于排序、搜索和复制数组的方法。
Array 类是提供创建、操作、搜索和排序数组的方法,
int LengthOfNumbers = a.Length;
System.Array 类提供许多有用的其他方法 /属性 ,如用于排序、搜索和复制数组的方法。
Array 类是提供创建、操作、搜索和排序数组的方法,
在公共语言运行库中用作所有数组的基类;
了解一些
Array
类的方法和属性
.
Length.
Rank.
System.Collections.ArrayList
C#
里面数组是无法动态改变大小的,这是因为数组定义时声明的是
Array
类,而
Array
类是不能重新定义大小的。可以通过
Array.Copy
把旧的数据考到一个新的数组里
.
如果你想创建一个动态大小的数组,则可以用
ArrayList
类,如下:
System.Collections.ArrayList aa=new System.Collections.ArrayList() ;
System.Collections.ArrayList aa=new System.Collections.ArrayList() ;
ArrayList a=new ArrayList();
a.add("asdf");
a.add("asdf");
a.add("asdf");
a.add("asdf");
引用数组值:
string aa=Convert.ToString(a[0]);
string aa=Convert.ToString(a[0]);
在使用的时候,可以用 aa.Add 方法向里面添加元素, Remove 删除元素,可以向数组下标一样访问,不过在使用的时候,最好对一个元素进行类型的强制转换。
6-3.
区别数组本身和数组的元素
.
6-4.
声明和实例化同时进行
?
6-5.
动态数组
?
6-6.
数组元素的类型转换
?
6-7.Foreach
和
for
遍历的区别
?
6-8.
什么时候用数组
?
数值数组元素的默认值设置为零,而引用元素的默认值设置为
null
。
交错数组是数组的数组,因此,它的元素是引用类型,初始化为
null
。
数组的索引从零开始:具有
n
个元素的数组的索引是从
0
到
n-1
。
数组元素可以是任何类型,包括数组类型。
new
运算符用于创建数组并将数组元素初始化为它们的默认值。
可以在声明数组时将其初始化,也可以初始化数组但不指定级别
,
如果选择声明一个数组变量但不将其初始化,必须使用
new
运算符将一个数组分配给此变量。
可以将初始化的一维多维数组传递给方法。也可以在一个步骤中初始化并传递新数组。
使用数组类型的
out
参数前必须先为其赋值,即必须由被调用方为其赋值。
数组类型的
ref
参数必须由调用方明确赋值。因此不需要由接受方明确赋值。可以将数组类型的
ref
参数更改为调用的结果。
Out
例题
:
class TestOut
{
static void FillArray(out int[] arr)
{
arr = new int[5] { 1, 2, 3, 4, 5 };
}
static void Main()
{
int[] theArray; // Initialization is not required
// Pass the array to the callee using out:
FillArray(out theArray);
// Display the array elements:
System.Console.WriteLine("Array elements are:");
for (int i = 0; i < theArray.Length; i++)
{
System.Console.Write(theArray[i] + " ");
}
}
}
Ref
例
:
class TestRef
{
static void FillArray(ref int[] arr)
{
// Create the array on demand:
if (arr == null)
{
arr = new int[10];
}
// Fill the array:
arr[0] = 1111;
arr[4] = 5555;
}
static void Main()
{
// Initialize the array:
int[] theArray = { 1, 2, 3, 4, 5 };
// Pass the array using ref:
FillArray(ref theArray);
// Display the updated array:
System.Console.WriteLine("Array elements are:");
for (int i = 0; i < theArray.Length; i++)
{
System.Console.Write(theArray[i] + " ");
}
}
}