C#Array基类的部分成员及使用
开发工具与技术:工具:Visual Studio/c#,技术:C#
作者:刘胜
撰写时间:2019-02-17
Array基础知识—Array类的属性和方法,如下:
1、Clear() 这个静态方法将数组中一系列元素设置为空值(值项为0,对象引用为NULL,布尔值为false)
2、CopyTo() 这个方法用来将源数组中的元素复制到目标数组中
3、Length 这个属性返回当前数组中项的个数
4、Rank 这个属性返回当前数组维数
5、Reverse() 这个静态方法反转一维数组的内容
6、Sort() 这个静态方法为内建类型的一维数组排序。
如果数组中的元素实现了IComparer接口,我们就可以为自定义类型排序
实例
下面的程序演示了Array类的一些方法的用法:
//实例
static void Main(string[] args)
{
SystemArrayFunctionality();
Console.ReadLine();
}
static void SystemArrayFunctionality()
{
Console.WriteLine("=> Working with System.Array.");
// 初始化起始项
string[] gothicBands = { "Tones on Tail", "Bauhaus", "Sisters of Mercy" };
// 按声明的次序输出名字
Console.WriteLine("-> Here is the array:");
for (int i = 0; i < gothicBands.Length; i++)
{
// 输出一个名字
Console.Write(gothicBands[i] + ",");
}
Console.WriteLine("\n");
// 反转它们
Array.Reverse(gothicBands);
Console.WriteLine("-> The reversed array");
// 输出它们
for (int i = 0; i < gothicBands.Length; i++)
{
// 输出一个名字
Console.Write(gothicBands[i] + ", ");
}
Console.WriteLine("\n");
// 清除除了最后成员之外的所有项
Console.WriteLine("-> Cleared out all but one...");
Array.Clear(gothicBands, 1, 2);
for (int i = 0; i < gothicBands.Length; i++)
{
// 输出一个名字
Console.WriteLine(gothicBands[i] + ", ");
}
Console.WriteLine();
}
当上面的代码被编译和执行时,它会产生下列结果:
小结
Array类提供创建、操作、搜索和排序数组的方法,因而在公共语言运行时中用作所以数组的基类,同时也是个抽象类。