zoukankan      html  css  js  c++  java
  • C# 数组

    二维数组由若干个一维数组组成。

    在C++中,组成二维数组的一维数组长度必须相等。在C#中却可以不相等。

    C#二维数组有两种:

    1,普通二维数组:

    int [,] arr2d = new int[3,2];
    int[,] scroes2d2 = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };

    2,数组的数组:又称锯齿数组,交错数组

    int[][] varr = new int[3][] //不能写成int[][] varr = new int[3][2]
    int[][] varr2 = new int[3][] { new int[1] { 1 }, new int[3] { 1, 2, 3 }, new int[2] { 1, 2 } };

    测试代码:

    class Program
        {
            static void Main(string[] args)
            {
                int[] scroes = new int[5];
                int[,] scroes2d = new int[3,2];
                Console.WriteLine("scroes2d.length:{0}", scroes2d.Length); //6
                for(int i=0; i<3; ++i)
                {
                    for(int j=0; j<2; ++j)
                    {
                        scroes2d[i, j] = i * 2 + j;
                    }
                }
    
                int[][] varr = new int[3][];
                Console.WriteLine("varr.length:{0}", varr.Length); //3
                for(int i=0; i<varr.Length; ++i)
                {
                    varr[i] = new int[i + 1];
                    for(int j=0; j<varr[i].Length; ++j)
                    {
                        varr[i][j] = j;
                    }
                }
                foreach(var arr in varr)
                {
                    foreach(var n in arr)
                    Console.Write(n);
                    Console.WriteLine();
                }
                Console.ReadKey();
            }
    
        }
    • 附:参数数组

    有时,当声明一个方法时,您不能确定要传递给函数作为参数的参数数目。C# 参数数组解决了这个问题,参数数组通常用于传递未知数量的参数给函数。

    在使用数组作为形参时,C# 提供了 params 关键字,使调用数组为形参的方法时,既可以传递数组实参,也可以只传递一组数组。params 的使用格式为:

    public 返回类型 方法名称( params 类型名称[] 数组名称 )

        class CTest
        {
            public void func(params int[] arr)
            {
                foreach(var n in arr)
                {
                    Console.Write(n + ",");
                }
            }
        }
        class Program
        {
            static void Main(string[] args)
            {

                  CTest ot = new CTest();
                  ot.func(1,2,3,4,5,6,7,8,9,0);
                  ot.func(new int[] { 1, 2, 3, 4 });

         }
            }

  • 相关阅读:
    解决 vs2010 安装过程 提示序列号非法问题
    下载文件(弹出迅雷来下载)
    UrlRewriter URL重写
    C#加密算法汇总
    js 平时经常用的
    c# 解析txt 统计
    漂亮的后台 模板
    无限级分类 父节点 子节点
    FlyTreeView for asp.net (4.4.1.2最新破解版)
    jQueryJSON 无刷新三级联动
  • 原文地址:https://www.cnblogs.com/timeObjserver/p/5926084.html
Copyright © 2011-2022 走看看