获取多维数组的维度

实现效果:

  

知识运用:

  获取数组的行与列运用了Array类的GetUpperBound(int dimension)方法,用来获取指定维度的上限;

  使用GetUpperBound(0)+1获取数组的行数,使用GetUpperBound(1)+1获取数组的列数; 

实现代码:

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Clear();    //清空之前内容
            Random ran=new Random();
            string[,] str_array = new string[ran.Next(2, 10), ran.Next(2, 10)];//定义随机数组
                label1.Text = string.Format("生成了{0}行{1}列的数组",
                    str_array.GetUpperBound(0)+1,str_array.GetUpperBound(1)+1);
                show_array(str_array);  //调用显示
        }
        //定义显示方法
        public void show_array(string[,] arr) { 
            for(int i=0;i<arr.GetUpperBound(0)+1;i++){
                for (int j = 0; j < arr.GetUpperBound(1) + 1;j++ )
                {
                    arr[i,j] = string.Format("{0},{1}  ",i,j);
                    textBox1.AppendText(arr[i, j]);
                }       textBox1.AppendText("\n");  //进行换行
            } textBox1.BackColor = Color.Honeydew;  //添加背景色
        }

猜你喜欢

转载自www.cnblogs.com/feiyucha/p/10055405.html