📄 sample4.cs
字号:
namespace apibook
{
using System;
public class TestArray
{
public static void Main()
{
Array testArray= Array.CreateInstance (typeof(string),2,3);
//创建一个2行3列的字符串数组
Console.WriteLine("打印所有元素");
PrintValues(testArray);
Console.WriteLine("打印完,没有设置值,所以是空引用");
Console.WriteLine("设置元素值。");
testArray.SetValue("a0",0,0);
//使用SetValue方法对数组的元素进行设置
testArray.SetValue("a1",0,1);
testArray.SetValue("a2",0,2);
testArray.SetValue("b0",1,0);
testArray.SetValue("b1",1,1);
testArray.SetValue("a2",1,2);
Console.WriteLine("第1行的所有元素是:"+testArray.GetValue(0,0)
+","+testArray.GetValue(0,1)+","+testArray.GetValue(0,2));
Console.WriteLine("testArray的长度是:"+testArray.GetLength(0));
//调用GetLength方法来获得该数组长度
Console.WriteLine("testArray的下限是:"+testArray.GetLowerBound(0));
//调用GetLowerBound方法获取testArray第一维的下限
Console.WriteLine("testArray的上限是:"+testArray.GetUpperBound(0));
//调用GetUpperBound方法获取testArray第一维的上限
Array testCopyArray= Array.CreateInstance(typeof(string),3,4);
//创建一个3行4列的数组进行拷贝操作
for ( int i = testCopyArray.GetLowerBound(0); i <= testCopyArray.GetUpperBound(0); i++ )
{
testCopyArray.SetValue("0",i,0);
testCopyArray.SetValue("0",i,1);
testCopyArray.SetValue("0",i,2);
testCopyArray.SetValue("0",i,3);
}
//对testCopyArray进行初始化操作
Console.WriteLine("打印testCopyArray现有元素值:");
PrintValues(testCopyArray);
Console.WriteLine("打印testArray的所有元素:");
PrintValues(testArray);
Array.Copy(testArray,testCopyArray,3);
//使用Copy方法拷贝testArray的前三个元素到testCopyArray的前三个元素处
Console.WriteLine("将testArray的前三个元素值拷贝到testCopyArray的前三个元素:");
Console.WriteLine("再打印testCopyArray的所有元素:");
PrintValues(testCopyArray);
Array testIndexArray=Array.CreateInstance(typeof(string),5);
for ( int j = testIndexArray.GetLowerBound(0); j <= testIndexArray.GetUpperBound(0); j++ )
{
testIndexArray.SetValue("0",j);
}
Console.WriteLine("打印testIndexArray数组:");
PrintValues(testIndexArray);
Console.WriteLine("testCopyArray里第一个出现0的索引是:"+Array.IndexOf(testIndexArray,"0"));
//使用IndexOf方法
Console.WriteLine("testCopyArray里最后出现0的索引是:"+Array.LastIndexOf(testIndexArray,"0"));
//使用LastIndexOf方法
}
public static void PrintValues( Array printArray )
{
System.Collections.IEnumerator myEnumerator = printArray.GetEnumerator();
//使用GetEnumerator方法获取printArray的IEnumerator对象。
int i = 0;
int cols = printArray.GetLength ( printArray.Rank - 1 );
//使用GetLength方法获取数组的长度
while ( myEnumerator.MoveNext() )
{
if ( i < cols )
{
i++;
}
else
{
Console.WriteLine();
i = 1;
}
Console.Write(myEnumerator.Current+" " );
}
Console.WriteLine();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -