C#获取多维数组的行数与列数

来源:互联网 发布:淘宝aj厂货店铺 编辑:程序博客网 时间:2024/06/06 02:38

效果图:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        public void button1_Click(object sender, EventArgs e)
        {
            textBox1.Clear();                                               //清空字符串
            string[,] g;


            Random j = new Random();
            int m = j.Next(2, 10);
            int n = j.Next(2, 10);
            g = new string[m, n];                                             //随机生成二维数组
            label1.Text = string.Format("生成了{0}行{1}列的数组", g.GetUpperBound(0) + 1, g.GetUpperBound(1) + 1);              //获取数组的行数与列数
            for (int a = 0; a < g.GetUpperBound(0) + 1; a++)
            {
                for (int b = 0; b < g.GetUpperBound(1) + 1; b++)                //依次输出二维数组内数据
                {
                    textBox1.Text += a + ","+b+"  ";
                }
                textBox1.Text += System.Environment.NewLine;
            }
                
        }
    


        //GetUpperBound
        // 摘要:
        //     获取 System.Array 的指定维度的上限。
        //
        // 参数:
        //   dimension:
        //     System.Array 的从零开始的维度,其上限需要确定。
        //
        // 返回结果:
        //     System.Array 中的指定维度的上限。
        //
        // 异常:
        //   System.IndexOutOfRangeException:
        //     dimension 小于零。 - 或 - dimension 等于或大于 System.Array.Rank。
        
    }
}

Array类是公共语言运行库中所有数组的基类,提供创建、操作、搜索和排序数组的方法,GetUpperBound方法用来获取array数组的制定维度上限

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

资源下载地址:http://download.csdn.net/detail/qq_28597703/8959503

1 0