企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
> c#中的数组都是由systerm.array类派生而来的引用对象。 ![](https://ws4.sinaimg.cn/large/006tKfTcgy1frahs2ftioj30lf0byjts.jpg) # 一维数组表达 用new给数组初始化。 ``` int[] arr = new int[3]; // 只定义数组的长度,不定义具体内容,是可行的 ``` # 常见错误 1. `int arr[] = new int[3];` 错在[]位置写错,应该是int[] arr 2. `int[] arr = new int[3] {1,2 }` 错在如果定义了数组长度是3,但初始化的时候只有2个数,那么会提示错误。 3. `int[] arr = new string[3]` 错在左边定义了int类型,右边又定义了string类型,相冲突。 ## 例如:输入每个月天数 并输出 ``` int[] arr = new int[12] {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 30} int i; // 用来指代数组第n个数 for(i=0, i<12; i++) { console.writeline( (i+1) + "月份为" + arr[i]); //数组编号从0开始,故i编号为0-11. console.write 的表达 } console.readline(); ``` ![](https://box.kancloud.cn/6afc05640ff8dec596c337ed22a77478_673x331.png) ![](https://box.kancloud.cn/3153e835bd3cce06863c6b1f39c1212a_677x442.png) # 二维数组表达 `int [ , ] ` 或` string [] []` 一般用第一种方法 `int[,] arr = new int [2, ]` 因为第二种方法也叫不规则数组,没法指定列数。否则代码错。 CS0178 C# Invalid rank specifier: expected ',' or ']' 无效的秩说明符:应为“,”或“]” ``` int[, ] arr = new int[2, ]; //不指定列数 a[0] = new int[2]; //第0行有2列 a[1] = new int[4]; //第1行有4列 ``` ![](https://box.kancloud.cn/2515c5b05b0b922e5e5753967f21ddc2_725x510.png) 数组可以有多维。 ## 初始化二维数组 ``` int[ , ] arr = {{12,12}, {13,13}, {14,14}}; //这里右边不能再写new,否则错误 int[ , ] arr = new int[] {{12,12}, {13,13}, {14,14}}; //这样才对 ``` ![](https://box.kancloud.cn/bb384108c5da50edcef5894663fc5ee4_1059x607.png) ## 数组转置 比如 ![](https://box.kancloud.cn/f360799d627f0e3053131abd3c41baba_131x61.png) ![](https://box.kancloud.cn/7f7c20828c428ea6b34c42c43afae3b4_885x747.png) ``` int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int i, j; Console.WriteLine("原始数组"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { Console.Write(arr[i, j] + " "); } Console.WriteLine(); } int temp; for(i=0;i<3;i++) { for(j=0;j<i;j++) { temp = arr[i, j]; arr[i, j] = arr[j, i]; arr[j, i] = temp; } } Console.WriteLine("修改后的数组"); for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { Console.Write(arr[i, j] + " "); } Console.WriteLine(); } Console.ReadLine(); ``` # 直接调用systerm.array中的方法 ``` int[,] arr = new int[,]{}; console.writeline(arr.length); ``` ![](https://ws3.sinaimg.cn/large/006tKfTcly1frai0w057zj30bs01b0sq.jpg) 显示长度为9 ![](https://ws2.sinaimg.cn/large/006tKfTcly1frai4o9c5oj304103a0sp.jpg) ![](https://box.kancloud.cn/d9d5a7119ccaa93cf2aa59ece634c02a_836x398.png) copy copy to exists getlength getvalue reverse setvalue sort ## 正序排序 Array.Sort(arr); ## 反转排序 Array.Reverse; ## 倒序排序 Array.Sort(arr); Array.Reverse; # foreach 遍历数组来输出 ``` static void Main(string[] args) { int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int i, j; Console.WriteLine("原始数组"); foreach (int a in arr) // 这里的a只是我们随意定义的一个代词用来表示arr中的元素,也可以是其他名字 { Console.Write(a + " "); } Console.WriteLine("arr's length: "+arr.Length); Console.ReadLine(); } ``` 但这么执行以后,显示的就不是二维数组而是一维数组。 ![](https://ws3.sinaimg.cn/large/006tKfTcly1fraikp1v7lj308b01vq2z.jpg)