首页 > 代码库 > C#数组

C#数组

  1 using System;  2 using System.Collections.Generic;  3 using System.Linq;  4 using System.Text;  5 using System.Threading.Tasks;  6   7 namespace ArrayDemo  8 {  9     class Program 10     { 11  12         static void Main(string[] args) 13         { 14             //1 15             int[] myArray; 16             myArray = new int[4]; 17  18             //2 19             int[] myArray2 = new int[4]; 20  21             //3 22             int[] myArray3 = new int[4] { 1, 2, 3, 4 }; 23  24             //4 25             int[] myArray4 = new int[] { 1, 2, 3, 4 }; 26  27             //5 28             int[] myArray5 = { 1, 2, 3, 4 }; 29  30  31             //6 32             var myArray6 = new int[] { 1, 2, 3, 4 }; 33  34             int[] myArray7; 35             myArray7 = new int[] { 1, 3, 4 }; 36             int n = myArray7.Rank;//维度 37  38  39             Array intArray = Array.CreateInstance(typeof(int), 5); 40             for (int i = 0; i < intArray.Length; i++) 41             { 42                 intArray.SetValue(33, i); 43             } 44  45             for (int i = 0; i < 5; i++) 46             { 47                 Console.WriteLine(intArray.GetValue(i)); 48             } 49  50             //CreateInstance()方法有许多重载版本,可以创建多维数组和不基于0的数组 51             //下面的例子就创建一个包含2X3个元素的二维数组,第一维基于1,第二维基于10 52             int[] lengths = { 2, 3 }; 53             int[] lowerBounds = { 1, 10 }; 54             Array racers = Array.CreateInstance(typeof(Person), lengths, lowerBounds); 55             //SetValue()方法设置数组的元素,其参数是每一维的索引 56             racers.SetValue(new Person 57             { 58                 FirstName = "Alain", 59                 LastName = "Prost" 60             }, index1: 1, index2: 10); 61             racers.SetValue(new Person 62             { 63                 FirstName = "Emerson", 64                 LastName = "Fittipaldi" 65             }, 1, 11); 66             racers.SetValue(new Person 67             { 68                 FirstName = "Emerson", 69                 LastName = "Fittipaldi" 70             }, 1, 12); 71             racers.SetValue(new Person 72             { 73                 FirstName = "Emerson", 74                 LastName = "Fittipaldi" 75             }, 2, 10); 76             racers.SetValue(new Person 77             { 78                 FirstName = "Emerson", 79                 LastName = "Fittipaldi" 80             }, 2, 11); 81             racers.SetValue(new Person 82             { 83                 FirstName = "Emerson", 84                 LastName = "Fittipaldi" 85             }, 2, 12); 86  87  88             Console.ReadKey(); 89         } 90     } 91  92     // 93     public class Person 94     { 95         public string FirstName { get; set; } 96         public string LastName { get; set; } 97         public override string ToString() 98         { 99             return String.Format("{0} {1}", FirstName, LastName);100         }101     }102 }

 

C#数组